Skip to content

Instantly share code, notes, and snippets.

@agarthetiger
Created August 29, 2018 16:00
Show Gist options
  • Save agarthetiger/520f281d6519506032a94d0445eba9d0 to your computer and use it in GitHub Desktop.
Save agarthetiger/520f281d6519506032a94d0445eba9d0 to your computer and use it in GitHub Desktop.
Referencing Env variables with a variable in a Jenkinsfile
// I wrote a Jenkinsfile shared library method to check job parameters for mandatory fields. The
// list of mandatory fields depended on other parameter values. Writing this as a reference because
// it wasn't immediately obvious how to use a (groovy) variable to access an env variable.
properties([
parameters([
string(name: 'MY_PARAM', defaultValue: '1.0.0', description: 'Useful description here.'),
])
])
node{
echo MY_PARAM // Prints '1.0.0' assuming the param is left as the default value
def mylist = ['MY_PARAM']
mylist?.each {
echo it // Prints 'MY_PARAM'
// echo $it // Error, no such property $it
echo 'env.${it}' // Prints 'env.${it}', single quotes do no variable interpolation
echo "env.${it}" // Prints 'env.MY_PARAM', variable interpolation on it but not for env
echo "$env.MY_PARAM" // Prints '1.0.0'
echo "$env.it" // Prints 'null'
echo "$env.${it}" // Prints 'org.jenkinsci.plugins.workflow.cps.EnvActionImpl@4ba0a01e.MY_PARAM'
// Solution
def myvar = env[it]
echo myvar // Prints '1.0.0'
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment