许多三方网站和应用能够与Jenkins交互,如Artifact仓库,基于云的存储系统和服务等. 在Jenkins中添加/配置credentials,Pipeline项目就可使用 credentials 与三方应用交互git
参考: https://jenkins.io/zh/doc/book/using/using-credentials/docker
Jenkins能够存储如下类型的credentials:shell
Secret text - API token之类的token (如GitHub我的访问token)api
Username and password - 能够为独立的字段,也能够为冒号分隔的字符串:username:password(更多信息请参照 处理 credentials)安全
Secret file - 保存在文件中的加密内容bash
SSH Username with private key - SSH 公钥/私钥对服务器
Certificate - a PKCS#12 证书文件 和可选密码ssh
Docker Host Certificate Authentication credentials.ide
为了最大限度地提升安全性,在Jenins中配置的 credentials 以加密形式存储在Jenkins 主节点上(用Jenkins ID加密),而且 只能经过 credentials ID
在Pipeline项目中获取gitlab
这最大限度地减小了向Jenkins用户公开credentials真实内容的可能性,而且阻止了将credentials复制到另外一台Jenkins实例
选择适合的凭证类型
建立 “Username and password” 凭证
建立 “SSH Username with private key” 凭证
在 ID 字段中,必须指定一个有意义的Credential ID
- 例如 jenkins-user-for-xyz-artifact-repository。注意: 该字段是可选的。 若是您没有指定值, Jenkins 则Jenkins会分配一个全局惟一ID(GUID)值。
请记住: 一旦设置了credential ID,就不能再进行更改。
参考: https://www.jenkins.io/doc/book/pipeline/jenkinsfile/#handling-credentials
存储在Jenkins中的credentials能够被使用:
适用于Jenkins的任何地方 (即全局 credentials),
经过特定的Pipeline项目/项目 (在 处理 credentials 和 使用Jenkinsfile部分了解更多信息),
由特定的Jenkins用户 (如 Pipeline 项目中建立 Blue Ocean的状况).
实际使用中,下面几个场景会用到creential
注意: 上述 Credential 类型都依赖于 jenkins插件,一样jenkins pipeline 也须要这些插件的安装以支持代码片断
Credentials Binding: https://plugins.jenkins.io/credentials-binding/
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" }
Jenkins Plain Credentials Plugin: https://plugins.jenkins.io/plain-credentials/
SSH Credentials: https://plugins.jenkins.io/ssh-credentials/
为了便于管理和使用, 强烈建议使用统一的约定来指定credential ID
建议使用相似下面的format作为credential ID, 便于jenkinsfile开发时直接使用,同时在”描述“里写清楚credential的做用
gitlab-api-token、gitlab-private-key、gitlab-userpwd-pair、harbor-xxx-xxx
实践:
以下所示,将凭证使用统一的ID命名以后,便于复用,凭证定义一次,可屡次,多个地方统一使用,不管是后期维护,复用都很是方便!
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"