groovy 如何在Jenkinsfile中创建有作用域的环境变量?

esbemjvw  于 2022-11-01  发布在  Jenkins
关注(0)|答案(1)|浏览(166)

Jenkins凭证插件提供了一个withCredentials函数,可以将凭证的值存储到一个作用域环境变量中,如here所示。

node {
  withCredentials([usernameColonPassword(credentialsId: 'mylogin', variable: 'USERPASS')]) {
    sh '''
      set +x
      curl -u "$USERPASS" https://private.server/ > output
    '''
  }
}

我想写一个groovy方法,存储在Jenkins vars共享库中,它可以做类似的事情;在函数作用域中,要操作的ID和存储该ID的环境变量名的对列表。

withMyOwnVars([
    ['some-input', 'VAR_NAME'],  // Value of VAR_NAME will be set under the hood somehow.
    ['another-one', 'VAR2']
])
{
    print("$VAR_NAME")
}

Groovy是否提供此功能?

91zkwejq

91zkwejq1#

一种实现方法是定义一个函数,该函数接收闭包旁边的输入参数(作为某种形式的键值),并使用evaluate函数在运行时定义给定的参数,从而使它们在闭包中可用。
类似于:

def withMyOwnVars(Map args, Closure body){
    args.each {
        // Define the name and value of the parameter. For strings, add quotes to make them evaluate correctly
        def paramName = it.key
        def paramValue = (it.value instanceof CharSequence) ? "'${it.value}'" : it.value

        // Run the evaluation of the parameter definition to make them available in the function's scope
        evaluate("${paramName} = ${paramValue}")
    }
    body()
}

// Usage will look like the following
withMyOwnVars(['myParam': 'my value', 'anotherParam': 6]) {
    println "I can now use myParam, and the value is ${myParam}"
    def result = 10 + anotherParam
}

或使用您要求的输入格式:

def withMyOwnVars(List args, Closure body){
    args.each { item ->
        def paramName = item[0]
        def paramValue = (item[1] instanceof CharSequence) ? "'${item[1]}'" : item[1]
        evaluate("${paramName} = ${paramValue}")
    }
    body()
}

// Usage will look like the following
withMyOwnVars([['myParam', 'my value'], ['anotherParam', 6]]) {
    println "I can now use myParam, and the value is ${myParam}"
    def result = 10 + anotherParam
}

相关问题