许多三方网站和应用可以与Jenkins交互,如Artifact仓库,基于云的存储系统和服务等. 在Jenkins中添加/配置credentials,Pipeline项目就可以使用 credentials 与三方应用交互
参考: https://jenkins.io/zh/doc/book/using/using-credentials/
Jenkins可以存储以下类型的credentials:
为了最大限度地提高安全性,在Jenins中配置的 credentials 以加密形式存储在Jenkins 主节点上(用Jenkins ID加密),并且 只能通过 credentials ID
在Pipeline项目中获取
这最大限度地减少了向Jenkins用户公开credentials真实内容的可能性,并且阻止了将credentials复制到另一台Jenkins实例
Credential ID
- 例如 jenkins-user-for-xyz-artifact-repository。注意: 该字段是可选的。 如果您没有指定值, Jenkins 则Jenkins会分配一个全局唯一ID(GUID)值。参考: https://www.jenkins.io/doc/book/pipeline/jenkinsfile/#handling-credentials
存储在Jenkins中的credentials可以被使用:
实际使用中,下面几个场景会用到creential
注意: 上述 Credential 类型都依赖于 jenkins插件,同样jenkins pipeline 也需要这些插件的安装以支持代码片段
environment {
MAGE_REPO_CREDENTIALS = credentials('COMPOSER_REPO_MAGENTO')
COMPOSER_AUTH = """{
"http-basic": {
"repo.magento.com": {
"username": "${env.MAGE_REPO_CREDENTIALS_USR}",
"password": "${env.MAGE_REPO_CREDENTIALS_PSW}"
}
} }"""
}
withCredentials([usernamePassword(credentialsId: 'amazon', usernameVariable: 'USERNAME', passwordVariable: 'PASSWORD')]) {
// available as an env variable, but will be masked if you try to print it out any which way
// note: single quotes prevent Groovy interpolation; expansion is by Bourne Shell, which is what you want
sh 'echo $PASSWORD'
// also available as a Groovy variable
echo USERNAME
// or inside double quotes for string interpolation
echo "username is $USERNAME"
}
gitlab-api-token、gitlab-private-key、gitlab-userpwd-pair、harbor-xxx-xxx
实践:
environment {
// HARBOR="harbor.devopsing.site"
HARBOR_ACCESS_KEY = credentials('harbor-userpwd-pair')
SERVER_ACCESS_KEY = credentials('deploy-userpwd-pair')
}
.....
docker login --username=${HARBOR_ACCESS_KEY_USR} --password=${HARBOR_ACCESS_KEY_PSW} ${HARBOR}
sshpass -p "${SERVER_ACCESS_KEY_PSW}" ssh -o StrictHostKeyChecking=no ${SERVER_ACCESS_KEY_USR}@${DEPLOY_SERVER} "$runCmd"