【问题标题】:How to get a Jenkins credential in a pipeline based on username part of the desired credential?如何根据所需凭据的用户名部分在管道中获取 Jenkins 凭据?
【发布时间】:2020-11-17 13:15:33
【问题描述】:

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

我有一个用例,我知道用户名是什么(基于存储用户名的 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 jenkins-pipeline credentials


    【解决方案1】:

    要在 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 与任何凭据不匹配

    【讨论】:

    • 嗨,谢谢,我以前使用过这种解决方法,但确实需要仔细检查是否有办法根据用户名或其他凭据字段值(不是 credentialId)选择 Jenkins 凭据
    • 查看我的编辑,并提供与您的用例相匹配的解决方法。
    • 它就像一个魅力。感谢您指出可能的警告和安全隐患。在我的情况下,它似乎以某种方式“com.cloudbees.plugins.credentials.CredentialsProvider.lookupCredentials(com.cloudbees.plugins.credentials.Credentials.class”脚本签名已被批准,因为这并没有阻止脚本执行。收集的凭据仍然被屏蔽在构建控制台中(这很好)。当然,我必须处理可能具有相同用户名或缺少一个的重复凭据条目。
    猜你喜欢
    • 1970-01-01
    • 2018-04-16
    • 2020-02-15
    • 2017-08-18
    • 2015-04-05
    • 2022-01-19
    • 1970-01-01
    • 2013-06-02
    • 2019-05-01
    相关资源
    最近更新 更多