首页 > 解决方案 > 如何在 Jenkins 共享变量中使用 Closure 创建包装 Jenkins withCredentials 的 withXCredentials?

问题描述

我想在我的管道脚本中使用这种语法的代码:

withXCredentials(id: 'some-cred-id', usernameVar: 'USER', passwordVar: 'PASS') {
   //do some stuff with $USER and $PASS
   echo "${env.USER} - ${env.PASS}"
}

请注意,您可以将任何代码放入其中withXCredenitals以执行。withXCredentials.groovy驻留在vars文件夹下的我的 Jenkins 共享库中,它将使用 Jenkins 原始文件withCredentials

//withXCredentials.groovy
def userVar = params.usernameVar
def passwordVar = params.passwordVar
def credentialsId = params.credentialsId

withCredentials([[$class: 'UsernamePasswordMultiBinding', credentialsId: credentialsId, usernameVariable: usernameVar, passwordVariable: passwordVar]]) {

        body()
}

我仍在学习高级的 groovy 东西,但我不知道如何做到这一点。

请注意

我的问题更多是关于 groovy 和 using 的语法,而这里Closure的答案不是我所追求的。使用该解决方案,我需要先实例化该类,然后再调用该方法。所以我试图避免做这样的事情:

new WithXCredentials(this).doSomthing(credentialsId, userVar, passwordVar)

在 Jenkins 文档中,它有一个使用闭包的示例:

// vars/windows.groovy
def call(Closure body) {
    node('windows') {
        body()
    }
}

//the above can be called like this:
windows {
    bat "cmd /?"
}

但它没有解释如何传递这样的参数

windows(param1, param2) {
    bat "cmd /?"
}

这里

标签: jenkinsgroovyjenkins-shared-libraries

解决方案


所以在挖掘互联网后,我终于找到了答案。万一有人需要同样的东西。以下代码将起作用:

// filename in shared lib: /vars/withXCredentials.groovy

def call(map, Closure body) {

    def credentialsId = map.credentialsId
    def passwordVariable =  map.passwordVariable
    def usernameVariable = map.usernameVariable
    withCredentials([[$class: 'UsernamePasswordMultiBinding', credentialsId: credentialsId, usernameVariable: usernameVariable, passwordVariable: passwordVariable]]) {
        echo 'INSIDE withXCredentials'
        echo env."${passwordVariable}"
        echo env."${usernameVariable}"
        body()
    }

}

有了这个,您的管道中可以有以下内容:

node('name') {
   withXCredentials([credentialsId: 'some-credential', passwordVariable: 'my_password', 
            usernameVariable: 'my_username']) { 
      echo 'Outside withXCredenitals'
      checkout_some_code username: "$env.my_username", password: "$env.my_password"
   }
}


推荐阅读