[英]Checkout Jenkins Pipeline Git SCM with credentials?
我正在关注本教程:
node {
git url: 'https://github.com/joe_user/simple-maven-project-with-tests.git'
...
}
但是,它没有说明如何添加凭据。 Jenkins 确实有特定的“凭据”部分,您可以在其中定义用户用户和密码,然后获取要在作业中使用的 ID,但是我如何在流水线指令中使用它?
我试过:
git([url: 'git@bitbucket.org:company/repo.git', branch: 'master', credentialsId: '12345-1234-4696-af25-123455'])
没有运气:
stderr: Host key verification failed.
fatal: Could not read from remote repository.
Please make sure you have the correct access rights
and the repository exists.
有没有办法在管道中配置凭证,或者我是否必须将 SSH 密钥放入 Jenkin 的 Linux 用户的 .ssh/authorized_keys 文件?
在理想的世界中,我希望有一个用于管道作业和 repo-keys 的存储库,然后启动 Docker Jenkins,并在那里动态添加这些作业和密钥,而无需在 Jenkins 控制台中配置任何内容。
您可以在管道中使用以下内容:
git branch: 'master',
credentialsId: '12345-1234-4696-af25-123455',
url: 'ssh://git@bitbucket.org:company/repo.git'
如果您使用的是 ssh url,那么您的凭据必须是用户名 + 私钥。 如果您使用的是 https 克隆网址而不是 ssh 网址,那么您的凭据应该是用户名 + 密码。
使用特定凭据显式结帐
stage('Checkout external proj') {
steps {
git branch: 'my_specific_branch',
credentialsId: 'my_cred_id',
url: 'ssh://git@test.com/proj/test_proj.git'
sh "ls -lat"
}
}
根据当前 Jenkins 作业中配置的凭据结帐
stage('Checkout code') {
steps {
checkout scm
}
}
您可以在单个 Jenkins 文件中使用这两个阶段。
如果要使用 ssh 凭据,
git(
url: 'git@github.com<repo_name>.git',
credentialsId: 'xpc',
branch: "${branch}"
)
如果要使用用户名和密码凭据,则需要使用@Serban 提到的 http clone。
git(
url: 'https://github.com/<repo_name>.git',
credentialsId: 'xpc',
branch: "${branch}"
)
使用 git 插件GitSCM 为您添加一个快速示例:
checkout([
$class: 'GitSCM',
branches: [[name: '*/master']],
doGenerateSubmoduleConfigurations: false,
extensions: [[$class: 'CleanCheckout']],
submoduleCfg: [],
userRemoteConfigs: [[credentialsId: '<gitCredentials>', url: '<gitRepoURL>']]
])
在你的管道中
stage('checkout'){
steps{
script{
checkout
}
}
}
对于值得添加到讨论中的内容......我所做的最终帮助了我......因为管道在每次运行时清理的 docker 映像内的工作区中运行。 我获取了对管道中的 repo 执行必要操作所需的凭据,并将它们存储在 .netrc 文件中。 这使我能够成功授权 git repo 操作。
withCredentials([usernamePassword(credentialsId: '<credentials-id>', passwordVariable: 'GIT_PASSWORD', usernameVariable: 'GIT_USERNAME')]) {
sh '''
printf "machine github.com\nlogin $GIT_USERNAME\n password $GIT_PASSWORD" >> ~/.netrc
// continue script as necessary working with git repo...
'''
}
它为我解决了使用
checkout scm: ([
$class: 'GitSCM',
userRemoteConfigs: [[credentialsId: '******',url: ${project_url}]],
branches: [[name: 'refs/tags/${project_tag}']]
])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.