Skip to content

Jenkins 配置 SSH Key

目标:让 Jenkins 能用 SSH 免密拉取 GitHub 仓库 用的是:git@github.com:xxx/xxx.git

🧩 总体流程(4 步)

1️⃣ Jenkins 服务器生成 SSH Key 2️⃣ 把公钥配置到 GitHub 3️⃣ 把私钥配置到 Jenkins Credentials 4️⃣ Pipeline 使用 SSH 地址拉代码

✅ 第一步:在 Jenkins 服务器生成 SSH Key

在 Jenkins 服务器上操作(你是 Windows):

打开 cmd 或 Git Bash

bash
ssh-keygen -t rsa -b 4096 -C "jenkins@yourcompany"

一路回车即可,默认生成在:

C:\Users\Administrator\.ssh\id_rsa
C:\Users\Administrator\.ssh\id_rsa.pub

确认文件存在:

bash
dir C:\Users\Administrator\.ssh

你会看到:

id_rsa
id_rsa.pub

✅ 第二步:把公钥添加到 GitHub

打开文件:

C:\Users\Administrator\.ssh\id_rsa.pub

内容类似:

ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQC...

复制整行内容。

去 GitHub:

👉 进入你的仓库 👉 Settings → Deploy keys → Add deploy key

填写:

  • Title: jenkins-key
  • Key: 粘贴刚才的公钥
  • ✅ 勾选:Allow write access(如果需要 push,不然可以不勾)
  • Add key

✅ 第三步:在 Jenkins 中添加 SSH 凭证

进入:

Manage Jenkins → Credentials → System → Global credentials → Add Credentials

填写:

  • Kind: SSH Username with private key
  • Username: git
  • Private Key: 选择 Enter directly
  • id_rsa 内容粘进去(不是 .pub,是私钥)
  • ID: github-ssh
  • Description: GitHub SSH Key

保存。

✅ 第四步:修改 Pipeline 使用 SSH 仓库地址

你的仓库地址要从:

https://github.com/bobo88/ycy88-new.git

改成:

git@github.com:bobo88/ycy88-new.git

Pipeline checkout 改成:

groovy
stage('Checkout') {
    steps {
        git branch: 'main',
            url: 'git@github.com:bobo88/ycy88-new.git',
            credentialsId: 'github-ssh'
    }
}

🧪 测试 SSH 是否成功(很重要)

在 Jenkins 服务器上执行:

bash
ssh -T git@github.com

第一次会问:

Are you sure you want to continue connecting (yes/no)?

输入:

yes

如果看到:

Hi bobo88! You've successfully authenticated

说明成功 🎉

⚠️ 常见坑(你很可能会遇到)

❌ 1. 没装 Git / 没有 ssh 命令

检查:

bash
ssh -V
git --version

如果没有,安装 Git for Windows。

❌ 2. Jenkins 服务用户不是 Administrator

你现在路径是:

C:\Users\Administrator\.jenkins

那 ssh key 就必须在:

C:\Users\Administrator\.ssh

否则 Jenkins 找不到。

❌ 3. 防火墙 / 公司网络拦截 22 端口

如果 22 端口被封,可以用 GitHub SSH 443 端口(进阶方案,我可以教你)。

✅ 完整最小可跑 Jenkinsfile 示例

groovy
pipeline {
    agent any

    stages {
        stage('Checkout') {
            steps {
                git branch: 'main',
                    url: 'git@github.com:bobo88/ycy88-new.git',
                    credentialsId: 'github-ssh'
            }
        }

        stage('Test') {
            steps {
                sh 'git log -1'
            }
        }
    }
}

🎯 成功标志

Console 中你会看到:

Fetching upstream changes from git@github.com:bobo88/ycy88-new.git
Checking out Revision ...

而不是:

Authentication failed