I have an environment var with default value
RUN_TESTS= true
My Jenkins job contains two stages, build and test stage. The test stage modified to run 2 kind of tests sets depended on RUN_TESTS value.
RUN_TESTS value is set on build stage.
Is there a way to update value for environment variable for future use ?
Here what I tried without success
env.RUN_TESTS= true
node("node1"){
sh '''
printenv
RUN_TESTS="false"
'''
}
print RUN_TESTS
I am getting
RUN_TESTS=false
[Pipeline] }
[Pipeline] // node
[Pipeline] echo
true
[Pipeline] End of Pipeline
CodePudding user response:
You can define your variable at the top of the jenkinsfile
environment {
RUN_TESTS=false
}
Then change it like this:
RUN_TESTS = true
with no ""
IF you are assigning this directly from the jenkinsfile. However, in your case, you are using it within and sh command, so you might have to use something like
${RUN_TESTS} = true
Although I haven't been able to test it so I can't give a guarantee that it will work.
CodePudding user response:
When you issue a sh
directive, a new instance of shell (most likely bash
) is created. As usual Unix processes, it inherits the environment variables of the parent. Notably, this includes RUN_TESTS
variable and its value. So a copy of Jenkins environment variable RUN_TESTS
is created for sh
directive.
Your bash
instance is then running your script. When your script sets or updates an environment variable, the environment of bash
is updated. Once your script ends, the bash
process that ran the script is destroyed, and all its environment is destroyed with it. Notably, this includes your updated RUN_TESTS
variable and its value. This has no influence on the Jenkins environment variable RUN_TESTS
that had its value copied before.
Here's a Python example demonstrating the same concept:
>>> def foo(i):
... print(i)
... i = 1
... print(i)
...
>>> i = 6
>>> i
6
>>> foo(i)
6
7
>>> i
6
The variable i
internal to function foo
was first initialized to 6, then incremented to 7, then destroyed. The outer variable bearing the same name i
was copied for the invocation of foo
but wasn't changed as a result.
CodePudding user response:
Use it like this
String RUN_TESTS = "true"
node("node1"){
sh '''
printenv
RUN_TESTS = "false"
'''
}
print RUN_TESTS