Ziv M
Ziv M

Reputation: 417

Jenkins set value for environment variable from one stage to be used in another

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

Upvotes: 3

Views: 4899

Answers (2)

Dashrath Mundkar
Dashrath Mundkar

Reputation: 9174

Use it like this

String RUN_TESTS = "true"

node("node1"){
    sh '''
    printenv
    RUN_TESTS = "false"
    '''
}
print RUN_TESTS

Upvotes: -1

MaratC
MaratC

Reputation: 6859

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.

Upvotes: 0

Related Questions