Jenkins Pipelines:如何从共享变量脚本中使用withCredentials()

时间:2018-07-13 16:57:31

标签: jenkins groovy jenkins-pipeline

我想在共享变量(“ vars /”)脚本中使用withCredentials()块,而不是直接在Jenkins管道中使用,因为这是特定库的低层语义,并且根据情况可能会也可能不需要。但是,withCredentials(或至少它的签名)似乎不在范围内。

脚本:

def credentials = [
    [$class: 'UsernamePasswordMultiBinding', credentialsId: '6a55c310-aaf9-4822-bf41-5500cd82af4e', passwordVariable: 'GERRIT_PASSWORD', usernameVariable: 'GERRIT_USERNAME'],
    [$class: 'StringBinding', credentialsId: 'SVC_SWREGISTRY_PASSWORD', variable: 'SVC_SWREGISTRY_PASSWORD']
]

withCredentials(credentials) {
// ...
}

控制台:

hudson.remoting.ProxyException: groovy.lang.MissingMethodException: No signature of method: BuildagentInstallAndRun.withCredentials() is applicable for argument types: (java.util.ArrayList, org.jenkinsci.plugins.workflow.cps.CpsClosure2) values: [[[$class:UsernamePasswordMultiBinding, credentialsId:6a55c310-aaf9-4822-bf41-5500cd82af4e, ...], ...], ...]

有人能成功吗?

3 个答案:

答案 0 :(得分:3)

我使用的是共享库而不是共享变量,但是我想这是类似的情况。 我没有使用$class参数,而是直接调用了管道摘要生成器建议的功能之一。您可以有一个列表here。在下面的示例中,我使用usernameColonPassword绑定。 在管道中,我实例化了类实用程序,并将this传递给了构造函数。然后,在库中,我使用step对象访问管道步骤(例如withCredentialsusernameColonPassword)。

class Utilities implements Serializable {
    def steps
    Utilities(steps) {
        this.steps = steps
    }
    def doArchiveToNexus(String credentials, String artifact, String artifact_registry_path){
        try {
            this.steps.withCredentials([steps.usernameColonPassword(credentialsId: credentials, variable: 'JENKINS_USER')]) {
                this.steps.sh "curl --user " + '${JENKINS_USER}' + " --upload-file ${artifact} ${artifact_registry_path}"
            }
        } catch (error){
            this.steps.echo error.getMessage()
            throw error
        }
    }
}

答案 1 :(得分:1)

您可以尝试以下操作:

import jenkins.model.*

credentialsId = '6a55c310-aaf9-4822-bf41-5500cd82af4e'

def creds = com.cloudbees.plugins.credentials.CredentialsProvider.lookupCredentials(
  com.cloudbees.plugins.credentials.common.StandardUsernameCredentials.class, Jenkins.instance, null, null ).find{
    it.id == credentialsId}

println creds.username 
println creds.password

但这并不安全,所有内容都将保存在控制台日志中

答案 2 :(得分:1)

我能够使用以下代码屏蔽正确的密码来在共享库中获取凭据:

class Utilities implements Serializable {
def steps
Utilities(steps) {
    this.steps = steps
}
def execute() {
    this.steps.withCredentials(
            bindings: [
                this.steps.usernameColonPassword(
                    credentialsId: this.credentialsId, 
                    variable: "unameColonPwd")
            ]) {
        this.steps.sh "echo {this.steps.env.unameColonPwd}"
    }
}