「Jenkins Pipeline」- 凭证管理、使用凭证

问题描述

在 Jenkins Pipeline 中,如果直接在脚本中使用明文的敏感信息(比如密钥、证书等等),会降低程序的可移植性、安全性;

该笔记将记录:在 Jenkins 中,如何正确管理和使用凭证,以提高程序的安全性和可移植性,避免直接使用私密信息?

解决办法

安装 Credentials Binding 插件,使得我们能够使用在 Jenkins 中配置的凭证信息。

在 Shell Script 中

RefereDocker Imagesnce global credentials in Bash script in Jenkins job

1)首先,添加凭证信息,将证书注入环境变量:

2)在 Shell Script 中,使用该变量即可(与环境变量引用方法相同);

在 Jenkins Pipeline 中

参考 Pipeline Steps Reference/Credentials Binding Plugin 手册,其列举大多数凭证的使用方法与获取方法;

使用 SSH 私钥文件

withCredentials([file(credentialsId: 'secret', variable: 'FILE')]) {
    sh 'use $FILE'
}

使用以冒号分隔的帐号密码

withCredentials([usernameColonPassword(credentialsId: 'mylogin', variable: 'USERPASS')]) {
	sh '''
	  set +x
	  curl -u "$USERPASS" https://private.server/ > output
	'''
}

使用字符串类型密钥

withCredentials([string(credentialsId: “CRET-ID”, variable: "varName")]){
    sh "echo $varName"
}

获取用户名密码

withCredentials([usernamePassword(credentialsId: "CRET-ID", usernameVariable: "username", passwordVariable: "password")]){
    sh "echo $username $password"
}

在共享库中,获取变量的方法

由 withCredentials 注入的“变量”(上述例子中的 FILE 与 USERPASS 变量),它们位于环境变量中的。

这意味着在「Jenkinsfile」与「共享库」中,获取这些变量的方法不同:
1)在 Jenkinsfile 中,需要从 env 中获取;
2)而在共享库中,需要将当前 Pipeline 传入共享库,然后在从中获取 env 中的环境变量。这一点可以参考「SSH」一文中的示例;

注意事项:这也导致在某些场景下,需要对$符号转义;

安全性

虽然代码中使用了这些变量,但是在 Jenkins 的 Console Output 中,会隐藏密码信息;

常见问题处理

控制凭证的访问权限

Stack Overflow/How Can I have job scope Credentials in Jenkins?

某些凭证,仅能供特定项目访问(Job)

通过 Folders plugin 与 Credentials Binding plugin 插件,将凭证现在特定目录和域中,以实现凭证的访问控制。

参考文献

Jenkins/Pipeline/Using a Jenkinsfile/Handling credentials
Pipeline Steps Reference/Credentials Binding Plugin
How to copy Jenkins secret file