能否通过自动化Pipeline作业添加或移除Jenkins凭据?
可以通过Pipeline自动化管理Jenkins凭据
完全可行,无需依赖Web界面,以下是两种常用的实现方式:
方法一:通过Groovy脚本调用Jenkins内部API
Jenkins的Credentials插件提供了内部API,可在Pipeline的script块中直接调用,实现凭据的增删操作。
添加凭据示例(用户名密码类型)
script { import com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl import com.cloudbees.plugins.credentials.CredentialsScope import jenkins.model.Jenkins // 定义凭据参数 def credId = 'new-credential-id' def username = 'test-user' // 注意:不要明文写密码,可从现有安全凭据中读取 def password = hudson.util.Secret.fromString('test-pass') def description = 'Automatically created via Pipeline' // 获取凭据存储 def store = Jenkins.instance.getExtensionList('com.cloudbees.plugins.credentials.SystemCredentialsProvider')[0].getStore() // 创建凭据对象 def credential = new UsernamePasswordCredentialsImpl( CredentialsScope.GLOBAL, credId, description, username, password ) // 添加凭据 store.addCredentials(jenkins.model.Domain.global(), credential) echo "凭据 ${credId} 添加成功" }
删除凭据示例
script { import com.cloudbees.plugins.credentials.CredentialsProvider import jenkins.model.Jenkins def credId = 'new-credential-id' // 查找目标凭据 def credential = CredentialsProvider.lookupCredentials( com.cloudbees.plugins.credentials.common.StandardCredentials.class, Jenkins.instance, null, null ).find { it.id == credId } if (credential) { def store = Jenkins.instance.getExtensionList('com.cloudbees.plugins.credentials.SystemCredentialsProvider')[0].getStore() store.removeCredentials(jenkins.model.Domain.global(), credential) echo "凭据 ${credId} 删除成功" } else { echo "未找到ID为 ${credId} 的凭据" } }
方法二:使用Credentials REST API
如果不想在Pipeline中嵌入Groovy脚本,也可以通过调用Jenkins的REST API实现操作,在Pipeline中用curl或httpRequest步骤发送请求:
添加凭据(示例用curl)
curl -X POST -u "admin:admin-token" \ -H "Content-Type: application/xml" \ http://jenkins-url/credentials/store/system/domain/_/createCredentials \ --data '<com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl> <scope>GLOBAL</scope> <id>new-api-cred</id> <description>Created via REST API</description> <username>api-user</username> <password>api-pass</password> </com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl>'
删除凭据
curl -X POST -u "admin:admin-token" \ http://jenkins-url/credentials/store/system/domain/_/credential/new-api-cred/doDelete
关键注意事项
- 权限控制:运行Pipeline的用户必须拥有
Credentials/Create、Credentials/Delete等权限,可通过Jenkins全局安全配置分配 - 敏感信息防护:禁止在Pipeline脚本或代码中明文存储密码,建议从现有安全凭据中读取敏感值
- 版本兼容性:不同Jenkins版本、Credentials插件版本的API可能存在差异,建议先在测试环境验证脚本
内容的提问来源于stack exchange,提问作者Raven
相关产品推荐
相关产品推荐

