如何根据所需凭据的用户名部分在管道中获取 Jenkins 凭据?

How to get a Jenkins credential in a pipeline based on username part of the desired credential?

有没有办法根据用户名而不是凭据 ID 获取 Jenkins 凭据?我的凭据类型为 username/password,具有全局范围。

我有一个用例,我知道用户名是什么(基于存储用户名的 JSON 文件,但它也可以在 jenkinsFile 中进行硬编码),我需要从中动态获取相应的密码Jenkins 凭据存储。

stage("Execute command based on schema"){
    withCredentials([usernamePassword(credentialsId: I_DONT_HAVE_THIS, passwordVariable: 'PASSWORD', usernameVariable: 'SCHEMA'])){
        sh "sqlplus \"$SCHEMA/$PASSWORD@DBNAME\" @/path/to/script.sql" 
    }
}

要在 Jenkins 中检索凭据,您必须提供 credentialsId,然后为 usernamepassword 设置变量名称。它们将链接到存储在凭据管理器中的适当用户名和密码。

这样,如果凭据正确存储在 Jenkins 中,您可以将用户名设置为 id,以便凭据检索正确的用户名和密码。

我认为这对于您的用例是可行的,因为您必须在 运行 您的管道之前存储凭据,并且您可以根据需要设置 id

编辑 有解决方法

如果您真的想使用 username 获取凭据,您可以使用变通方法获取所有凭据的列表并匹配适当的 username :

stage("Execute command based on schema") {
    steps {
        script {
            // Set this variable which should match with the user in credentials
            def schema = "usertest"
            def credential_id = ""
            def creds = com.cloudbees.plugins.credentials.CredentialsProvider.lookupCredentials(
                com.cloudbees.plugins.credentials.common.StandardUsernameCredentials.class,
                Jenkins.instance,
                null,
                null
            );
            for (c in creds) {
                if (c.username == schema) {
                    credential_id = c.id
                }
            }
                
            withCredentials([usernamePassword(credentialsId: credential_id, passwordVariable: 'PASSWORD', usernameVariable: 'SCHEMA')]) {
                sh 'sqlplus \"$SCHEMA/$PASSWORD@DBNAME\" @/path/to/script.sql'
            }
        }
    }
}

请注意存在一些安全问题:

  • 您需要在管理员端激活大量脚本(参见script-approval
  • 任何可以访问脚本的人都可以在循环中调用所有凭证字段,如 iddescriptionusernamepassword(他们将 不被屏蔽)
  • 如果 username 与任何凭据不匹配,您应该管理错误