如何在Jenkinsfile声明式流水线中获取已存储的Jenkins凭证?
Jenkins声明式流水线中凭证的两种使用方式
先给你纠正代码里的一个关键错误:声明式流水线的parameters不能放在stage的steps里,必须移到pipeline块下,和agent、environment同级,否则参数不会生效。
回到凭证的问题,你看到的两种用法都可行,具体选哪种看场景:
1. 在environment块全局定义凭证
这种方式适合整个流水线(或多个stage)都需要用到该凭证的场景,定义一次后所有stage都能直接调用。
用法说明
当你在environment里用credentials('x-credentials-id')定义时:
- 如果是用户名密码类型的凭证,Jenkins会自动生成两个环境变量:
my_credentials_USR(用户名)和my_credentials_PSW(密码) - 如果是文本密钥类型的凭证,直接用
my_credentials就能获取完整密钥内容
修正后的示例代码
pipeline { agent any // 参数要放在这里,和agent、environment同级 parameters([ string(name: 'a', defaultValue: 'x', description: 'test'), text(name: 'b', defaultValue: ''), text(name: 'b2', defaultValue: ''), text(name: 'c', defaultValue: ''), text(name: 'c2', defaultValue: '') ]) environment { // 全局定义凭证 my_credentials = credentials('x-credentials-id') } stages { stage('使用全局凭证') { steps { script { // 打印用户名(仅示例,实际不要明文输出密码) echo "用户名:${my_credentials_USR}" // 如果是文本密钥,直接用my_credentials // echo "密钥内容:${my_credentials}" } } } stage('另一个使用凭证的Stage') { steps { // 这里也能直接调用my_credentials_USR和my_credentials_PSW sh "echo 使用用户名:${my_credentials_USR}" } } } }
2. 在stage内用withCredentials块调用
这种方式适合只有单个stage需要用到凭证的场景,更灵活,还能支持多种特殊凭证类型(比如SSH密钥、文件凭证)。
用法说明
用withCredentials包裹需要使用凭证的步骤,指定凭证类型(比如usernamePassword、string、sshUserPrivateKey等),并绑定到自定义变量名。
示例代码
pipeline { agent any parameters([ string(name: 'a', defaultValue: 'x', description: 'test'), text(name: 'b', defaultValue: ''), text(name: 'b2', defaultValue: ''), text(name: 'c', defaultValue: ''), text(name: 'c2', defaultValue: '') ]) stages { stage('仅当前Stage使用凭证') { steps { withCredentials([ // 用户名密码类型,绑定到自定义变量 usernamePassword( credentialsId: 'x-credentials-id', usernameVariable: 'USER', passwordVariable: 'PASS' ), // 如果是文本密钥类型 // string(credentialsId: 'secret-text-id', variable: 'SECRET_KEY') ]) { script { echo "用户名:${USER}" // 用密码执行命令,比如登录某个服务 sh "some-command --user ${USER} --pass ${PASS}" } } } } } }
选择建议
- 如果多个stage都要用到同一个凭证,优先用
environment全局定义,减少重复代码 - 如果只有单个stage需要,或者需要使用特殊类型的凭证(比如SSH密钥、文件),用
withCredentials更合适
内容的提问来源于stack exchange,提问作者Andreia
相关产品推荐
相关产品推荐

