Raven
Raven

Reputation: 1520

How can I create scoped environment variables in my Jenkinsfile?

The Jenkins credentials plugin provides a withCredentials function that can store the value of a credential into a scoped environment variable as seen here.

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

I want to write a groovy method we store in our Jenkins vars shared library that does something similar; a list of pairs for an ID to operate on and the name of an environment variable to store that ID within scope of the function. Something like

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

Does Groovy provide this functionality?

Upvotes: 0

Views: 420

Answers (1)

Noam Helmer
Noam Helmer

Reputation: 6824

One way to achieve what you want is to define a function that receives the input parameters (as some form of key value) alongside a Closure and uses the evaluate function to define the given parameters at runtime, thus making them available inside the closure.

Something like:

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
}

Or using your requested input format:

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
}

Upvotes: 1

Related Questions