温馨提示×

centos jenkins怎样集成git

小樊
42
2026-09-09 08:10:51
栏目: 智能运维

CentOS 上让 Jenkins 集成 Git,通常分为以下几个步骤:安装 Git、安装 Jenkins Git 插件、配置 Jenkins 使用 Git、创建任务并拉取代码。下面给你一个常见且实用的完整流程


一、在 CentOS 上安装 Git

sudo yum install -y git

验证:

git --version

二、Jenkins 安装 Git 插件

  1. 登录 Jenkins
  2. 进入:
    Manage Jenkins → Manage Plugins → Available
    
  3. 搜索 Git Plugin
  4. 勾选并安装(一般默认已安装)
  5. 安装完成后重启 Jenkins(可选)

三、配置 Jenkins 的 Git 路径

  1. 进入:
    Manage Jenkins → Global Tool Configuration
    
  2. 找到 Git
  3. 点击 Add Git
    • Name: Default
    • Path to Git executable: /usr/bin/git
  4. 保存

四、配置 Git 凭据(重要)

1️⃣ 使用用户名 + 密码(HTTP)

Manage Jenkins → Credentials → System → Global credentials

添加:

  • Kind: Username with password
  • Username: git 用户名
  • Password: 密码 / Token
  • ID: git-creds

2️⃣ 使用 SSH Key(推荐)

ssh-keygen -t rsa -C "jenkins@centos"

~/.ssh/id_rsa.pub 加到 Git 服务器(GitHub / GitLab)。

Jenkins 中添加:

  • Kind: SSH Username with private key
  • Private Key: 粘贴 id_rsa

五、创建 Jenkins 任务并集成 Git

  1. 新建任务(Freestyle / Pipeline)
  2. Source Code Management
    • 选择 Git
    • Repository URL:
      https://github.com/user/repo.git
      或
      git@github.com:user/repo.git
      
    • Credentials:选择上面创建的
    • Branch:*/main*/master

六、测试构建

Build Steps 中加一条:

echo "Git Pull Success"
git log -1

点击 Build Now,查看控制台输出。


七、常见问题

❌ Jenkins 找不到 git

git: command not found

✅ 解决:Global Tool Configuration 中填 /usr/bin/git

❌ Permission denied (publickey)

✅ 检查:

  • Jenkins 用户是否有 .ssh
  • 公钥是否加到 Git 服务器

❌ Host key verification failed

sudo -u jenkins ssh-keyscan github.com >> ~/.ssh/known_hosts

八、Pipeline 示例(可选)

pipeline {
    agent any
    stages {
        stage('Checkout') {
            steps {
                git branch: 'main',
                    url: 'git@github.com:user/repo.git',
                    credentialsId: 'git-ssh'
            }
        }
    }
}

如果你愿意,我可以:

  • 给你 Jenkins + GitLab 专用配置
  • 教你 Webhook 自动触发构建
  • 或帮你写 完整 CI 流水线

你现在是 GitHub / GitLab / Gitee 哪一个?

0