温馨提示×

jenkins如何连接git仓库

小樊
59
2026-10-16 17:48:50
栏目: 编程语言

在 Jenkins 中连接 Git 仓库,通常分为基础配置和任务中使用两部分。下面以最常见的 Git + Jenkins Freestyle / Pipeline 为例说明。


一、前置准备

1. 安装 Git 插件

Jenkins 默认一般已安装 Git Plugin,如果没有:

  • 进入 Manage Jenkins → Manage Plugins → Available
  • 搜索 Git 并安装

2. 服务器安装 Git

Jenkins 所在服务器需安装 Git:

# CentOS
yum install git -y

# Ubuntu
apt install git -y

# 验证
git --version

3. 准备 Git 仓库地址

  • HTTPS 地址:https://github.com/user/repo.git
  • SSH 地址:git@github.com:user/repo.git

二、配置 Git 凭据(重要)

方式一:HTTPS 用户名 + 密码 / Token

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

方式二:SSH 密钥(推荐)

  1. 在 Jenkins 服务器生成密钥:
ssh-keygen -t rsa -C "jenkins"
  1. 将 公钥 添加到 Git 仓库(GitHub / GitLab SSH Keys)
  2. Jenkins 中添加凭据:
    • 类型:SSH Username with private key
    • Username:git
    • Private Key:粘贴私钥内容

三、在 Jenkins 任务中连接 Git

1. Freestyle 项目

  1. 新建 Freestyle project
  2. 在 Source Code Management 中选择 Git
  3. 填写:
    • Repository URL:git@github.com:user/repo.git
    • Credentials:选择刚才配置的
  4. 指定分支(如 main / master)
  5. 保存并构建

2. Pipeline 项目

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

credentialsId 是在 Jenkins 凭据中配置的 ID


四、常见问题排查

1. Permission denied (publickey)

  • 私钥未正确配置
  • Jenkins 用户无权限访问密钥
  • Git 服务器未添加公钥

2. Host key verification failed

在 Jenkins 服务器执行:

git ls-remote git@github.com

确认 host key 已加入 known_hosts

3. 克隆超时

  • 检查网络
  • 使用国内镜像或使用 GitLab 内网地址

如果你愿意,可以告诉我:

  • 用的是 GitHub / GitLab / Gitee
  • 是 Freestyle 还是 Pipeline
  • 用 HTTPS 还是 SSH

我可以给你更具体的配置示例。

0 踩