温馨提示×

怎样集成git到jenkins

小樊
38
2026-10-19 16:34:48
栏目: 编程语言

将 Git 集成到 Jenkins 通常包含以下几个步骤:安装 Git、配置 Jenkins 的 Git 环境、创建 Jenkins 任务并关联 Git 仓库。下面按常见做法说明(以 Jenkins 2.x + Linux 为例,Windows / Docker 类似)。


一、前提条件

  1. 已安装 Jenkins
  2. 服务器已安装 Git
    git --version
    
    若未安装:
    • Ubuntu / Debian
      sudo apt update
      sudo apt install git
      
    • CentOS / RHEL
      sudo yum install git
      

二、在 Jenkins 中安装 Git 插件

  1. 登录 Jenkins
  2. 进入
    Manage Jenkins → Plugins(或 Manage Plugins)
  3. 在 Available plugins 中搜索:
    • Git
    • Git Client
  4. 勾选并点击 Install without restart

新版本 Jenkins 通常已默认安装 Git 插件


三、配置 Jenkins 的 Git 路径

  1. 进入
    Manage Jenkins → Tools(或 Global Tool Configuration)
  2. 找到 Git
  3. 点击 Add Git
    • Name:Default
    • Path to Git executable:
      • Linux 通常为 /usr/bin/git
      • 可执行 which git 查看
  4. 保存

四、配置 Git 凭据(用于私有仓库)

1. 使用用户名 + 密码 / Token

  1. Manage Jenkins → Credentials → System → Global credentials
  2. 点击 Add Credentials
  3. 类型选择:
    • Username with password
    • 或使用 Personal Access Token(GitHub / GitLab 推荐)
  4. 填写:
    • Username
    • Password / Token
  5. 保存

2. 使用 SSH 密钥(推荐)

  1. 生成密钥:
    ssh-keygen -t rsa -b 4096
    
  2. 将 公钥 添加到 Git 仓库(GitHub / GitLab / Gitee)
  3. 在 Jenkins 中添加:
    • Kind:SSH Username with private key
    • Private Key:粘贴 ~/.ssh/id_rsa

五、创建 Jenkins 任务并关联 Git

  1. 首页点击 New Item
  2. 输入名称,选择:
    • Freestyle project(简单)
    • 或 Pipeline(推荐)
  3. 在 Source Code Management 中选择:
    • ☑ Git
  4. 填写:
    • Repository URL:
      https://github.com/user/repo.git
      或
      git@github.com:user/repo.git
      
    • Credentials:选择刚配置的凭据
    • Branch:
      */main
      或
      */master
      

六、配置构建触发(可选)

常见方式:

  • Poll SCM
    H/5 * * * *
    
  • GitHub webhook / GitLab webhook(推荐)
  • Pipeline 中定时或手动触发

七、Pipeline 示例(可选)

pipeline {
    agent any
    stages {
        stage('Clone') {
            steps {
                git branch: 'main',
                    url: 'https://github.com/user/repo.git',
                    credentialsId: 'git-credentials-id'
            }
        }
        stage('Build') {
            steps {
                sh 'make'
            }
        }
    }
}

八、常见问题

✅ Jenkins 找不到 git

  • 检查 Git 路径配置
  • 确认 Jenkins 用户有执行权限

✅ Permission denied (publickey)

  • 检查 SSH key 是否添加到 Git 仓库
  • 检查 Jenkins 凭据类型是否正确

✅ Failed to connect repository

  • 网络问题
  • 防火墙 / 代理设置

如果你使用的是 GitHub / GitLab / Gitee / 内网 Git,或者 Docker 版 Jenkins,可以告诉我,我可以给你更具体的配置示例。

0 踩