温馨提示×

debian jenkins如何集成git

小樊
40
2026-09-02 02:06:48
栏目: 智能运维

在 Debian 上把 Jenkins 与 Git 集成,通常分为以下几个步骤:安装 Jenkins、安装 Git、安装 Jenkins Git 插件、配置凭据、创建 Job 并拉取代码。下面按实操流程说明。


一、环境准备

1. 安装 Git(Debian)

sudo apt update
sudo apt install git -y

验证:

git --version

2. 安装 Jenkins(Debian)

如果尚未安装 Jenkins:

sudo apt install openjdk-17-jdk -y

wget -q -O - https://pkg.jenkins.io/debian/jenkins.io.key | sudo apt-key add -
sudo sh -c 'echo deb http://pkg.jenkins.io/debian-stable binary/ > /etc/apt/sources.list.d/jenkins.list'

sudo apt update
sudo apt install jenkins -y

启动 Jenkins:

sudo systemctl enable jenkins
sudo systemctl start jenkins

访问:

http://<服务器IP>:8080

二、Jenkins 中安装 Git 插件

  1. 登录 Jenkins
  2. 进入 Manage Jenkins → Plugins → Available plugins
  3. 搜索 Git
  4. 安装:
    • Git
    • Git client
  5. 安装完成后重启 Jenkins

三、配置 Git 路径(通常自动识别)

  1. Manage Jenkins → Tools
  2. 查看 Git installations
  3. 若未自动识别,手动指定:
    Path to Git executable: /usr/bin/git
    

四、配置 Git 凭据(SSH / 账号密码)

方式一:SSH Key(推荐)

在 Jenkins 服务器生成密钥:

sudo -u jenkins ssh-keygen -t rsa -b 4096

查看公钥:

sudo -u jenkins cat /var/lib/jenkins/.ssh/id_rsa.pub

将公钥添加到:

  • GitHub / GitLab → SSH Keys

在 Jenkins 中添加凭据:

  1. Manage Jenkins → Credentials
  2. 添加:
    • Kind: SSH Username with private key
    • Username: git
    • Private Key: 粘贴 /var/lib/jenkins/.ssh/id_rsa

方式二:用户名密码 / Token

  • Kind: Username with password
  • 使用 Git 账号或 Personal Access Token

五、创建 Jenkins Job 并集成 Git

1. 新建 Job

  • New Item → Freestyle project

2. 配置源码管理

  • 选择 Git
  • Repository URL:
    git@github.com:user/repo.git
    
    https://github.com/user/repo.git
    
  • Credentials:选择前面配置的

3. 指定分支

*/main

*/master

六、构建测试

Build Steps 中添加:

git log -1
pwd
ls -l

点击 Build Now,查看控制台输出是否成功拉取代码。


七、常见集成场景

✅ Webhook 自动触发

  • GitHub / GitLab 配置 Webhook
  • Jenkins 安装 GitHub Integration 插件
  • Job 中勾选:
    • GitHub hook trigger for GITScm polling

✅ 多分支项目

  • 使用 Multibranch Pipeline
  • Jenkinsfile 中:
checkout scm

八、常见问题

1. Permission denied (publickey)

  • 确认 Jenkins 用户有 SSH key
  • 测试:
sudo -u jenkins git ls-remote git@github.com:user/repo.git

2. Git not found

  • 确认 /usr/bin/git 存在
  • Jenkins Tool 中正确配置

如果你需要:

  • Jenkinsfile 示例
  • GitLab / GitHub 具体 Webhook 配置
  • Pipeline 方式集成 Git

可以告诉我你的使用场景。

0