I'm using the Jenkins scripted pipeline and having trouble understanding how to nest environment variables within each other, here is a MWE:
// FROM https://jenkins.io/doc/pipeline/examples/#parallel-multiple-nodes
def labels = []
if (HOST == 'true') {
labels.add(<HOSTNAME>)
}
def builders = [:]
for (x in labels) {
def label = x
builders[label] = {
ansiColor('xterm') {
node(label) {
stage('cleanup') {
deleteDir()
}
stage('build') {
env.test = "TESTA"
env.intern = '''
TEST = "${env.test}"
'''
sh '''
echo $intern
printenv
'''
}
}
}
}
}
parallel builders
The idea here is that env.test
contains the value TESTA
, which sets env.intern
to TEST = TESTA
this is what I want to happen. After this the code is just to print out the values.
Sadly the result is TEST = "${env.test}"
.
How can I use nested string environment variables in Jenkins scripted pipeline?
CodePudding user response:
The syntax difference here is literal strings versus interpolated strings in Groovy versus shell interpreters within shell step methods.
"
: interpolated string in Groovy'
: literal string in Groovy and interpolated string in shell interpreter
Essentially, a Groovy variable is interpolated within "
in the pipeline execution, and an environment variable is interpolated within "
in the pipeline execution and within '
in the shell interpreter (and within the pipeline must also be accessed within the env
object, but is a first class variable expression in the shell step method).
Therefore, we can fix the assigned value of env.intern
with:
env.intern = "TEST = ${env.test}"
where the assigned value of env.test
will be interpolated within the Groovy string and assigned to the env
pipeline object at the intern
key. This will then also be accessible to the shell interpreter within shell step methods, and the rest of your pipeline is already correct and will behave as expected.
CodePudding user response:
Try the following:
env.intern = "TEST = ${env.test}"
As you're setting it now, the actual result of env.intern
will be "TEST= ${env.test}"
. So long as you set env.test
before you set env.intern
you should be good. Also, good to note that if you change the value of env.test
then you need to reset the value of env.intern
or it's going to hold the original value of env.test
that it was set to.