You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Jenkins:如何在配置Groovy代码中获取凭证(非流水线源码)

在Jenkins配置Groovy代码中获取凭证的方法

因为是在配置级Groovy里操作,没法用流水线的credentials()方法,直接调用Jenkins内部的凭证存储API就行,以下是不同凭证类型的实现:

1. 获取用户名密码类型凭证

import com.cloudbees.plugins.credentials.CredentialsProvider
import com.cloudbees.plugins.credentials.common.StandardUsernamePasswordCredentials

// 替换成你要获取的凭证ID
def targetCredentialId = 'example-cred-id'

// 从全局凭证存储中查找用户名密码类型凭证
def matchingCreds = CredentialsProvider.lookupCredentials(
    StandardUsernamePasswordCredentials.class,
    Jenkins.instance,
    null,
    null
)

// 根据ID定位目标凭证
def targetCred = matchingCreds.find { it.id == targetCredentialId }

if (targetCred) {
    def username = targetCred.username
    // Secret类型要转成字符串才能拿到明文
    def password = targetCred.password.toString()
    // 这里可以根据需求使用用户名和密码,比如输出或传入其他逻辑
    println "拿到用户名: ${username}, 密码: ${password}"
} else {
    println "没找到ID为${targetCredentialId}的用户名密码凭证"
}

2. 获取秘密文本类型凭证

如果是单条秘密字符串的凭证,用下面的代码:

import com.cloudbees.plugins.credentials.CredentialsProvider
import com.cloudbees.plugins.credentials.common.StandardSecretCredentials

def targetCredentialId = 'example-secret-id'

def matchingCreds = CredentialsProvider.lookupCredentials(
    StandardSecretCredentials.class,
    Jenkins.instance,
    null,
    null
)

def targetCred = matchingCreds.find { it.id == targetCredentialId }

if (targetCred) {
    def secretContent = targetCred.secret.toString()
    println "拿到秘密文本: ${secretContent}"
} else {
    println "没找到ID为${targetCredentialId}的秘密文本凭证"
}

关键注意点

  • 运行这段代码的账号必须有凭证读取权限,不然会拿不到数据或者报错
  • 所有Secret类型的内容必须调用toString(),直接输出Secret对象只会显示类似[secret]的占位符
  • 如果凭证存在Jenkins的某个文件夹下,不是全局存储,把Jenkins.instance换成对应的Folder实例就行

内容的提问来源于stack exchange,提问作者kristsam

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 12:24:51