要在 Jenkins Pipeline 脚本化中启用 SSH 密钥认证并克隆 Git 仓库,可以按照以下步骤进行配置。假设你已经在 Jenkins 中配置了 SSH 密钥认证,可以使用 Jenkins 凭据来安全地访问 Git 仓库。
步骤 1:配置 Jenkins 凭据
在 Jenkins 中,你需要确保已经配置了 SSH 密钥凭据。这里是如何配置SSH 密钥凭据:
- 进入 Jenkins 页面,点击 Manage Jenkins。
- 在 Manage Jenkins 页面点击 Manage Credentials。
- 选择 (Global),然后点击 Add Credentials。
- 在凭据类型中选择 SSH Username with private key。
填写必要的字段:
- Username:填写 Git 仓库的用户名。
- Private Key:选择 Enter directly 并粘贴你的私钥(确保私钥没有密码,或者如果有密码则提供密码)。
- 保存凭据并记下凭据 ID(例如 git-credentials)。
步骤 2:修改 Jenkins Pipeline 使用 SSH 密钥
在你的 Jenkins Pipeline 脚本中,你需要指定 SSH 凭据来克隆 Git 仓库。以下是一个使用 SSH 密钥认证的示例脚本:
pipeline {
agent any
environment {
// 在此指定你的凭据 ID,Jenkins 将自动选择凭据进行 SSH 认证
GIT_CREDENTIALS = 'git-credentials' // 替换为你在 Jenkins 凭据管理中配置的凭据 ID
}
stages {
stage('Clone Repository') {
steps {
// 使用 SSH 协议来克隆 Git 仓库
git(
url: 'git@gitlab.com:your-repo.git', // 使用 SSH 协议的 URL
branch: 'main',
credentialsId: "${GIT_CREDENTIALS}" // 指定 SSH 凭据 ID
)
}
}
stage('Build') {
steps {
echo 'Building the project...'
// 执行构建命令,例如:maven, npm
sh 'mvn clean package' // 如果是 Java 项目
}
}
stage('Test') {
steps {
echo 'Running tests...'
// 运行测试命令
sh 'mvn test'
}
}
stage('Deploy') {
steps {
echo 'Deploying application...'
// 部署脚本
sh './deploy.sh'
}
}
}
}
解释
-
git 步骤:在 Clone Repository 阶段,我们使用了 git 步骤来从 Git 仓库克隆代码。通过 credentialsId 参数来指定你在 Jenkins 上配置的 SSH 密钥凭据。
-
url 参数:我们使用了 SSH 协议的 URL,例如:git@gitlab.com:your-repo.git。这种方式可以通过 SSH 密钥进行认证,而不是使用 HTTP URL。
-
credentialsId:这里我们通过 credentialsId 指定了在 Jenkins 中配置的 SSH 凭据 ID(例如 git-credentials)。这样 Jenkins 会使用这个凭据来克隆代码。
步骤 3:确保 Jenkins 代理/主机上可以使用 SSH
如果 Jenkins 运行在一个代理节点上,请确保该节点上的 SSH 客户端已经配置好,并且可以通过 SSH 访问你的 Git 仓库。你可以在代理节点上运行以下命令进行测试:
ssh -T git@gitlab.com
如果一切正常,你应该看到类似于:
Hi <username>! You've successfully authenticated, but GitLab does not provide shell access.
步骤 4:运行 Pipeline
现在,你可以运行 Jenkins Pipeline 作业,Jenkins 会通过 SSH 密钥认证克隆代码,并继续执行后续的构建、测试和部署任务。
这样就配置好了一个支持 SSH 密钥认证的 Jenkins Pipeline。