I have following pipeline (content simplified, but the structure is exact):
pipeline {
agent any
environment {
my_var = ""
}
stages {
stage('Stage_parallel'){
parallel{
stage('Stage_1') {
steps {
...
}
}
stage('Stage_2'){
steps {
withCredentials([usernamePassword(<LOGIN>, <PASS>)])
{
sh'''
...
var_1 = "/path/to/folder"
var_2 = "file_name"
my_var = "${var_1}/${var_2}"
echo ${my_var} ### returns correct value
'''
}}}}}
stage('Stage_3'){
steps {
sh 'echo ${my_var}' ### returns ""
}}}}
So I tried to declare global variable, update it in Stage_2 and use in Stage_3. However, it returns correct value only in Stage_2 sh block, but not outside... I also tried to
pipeline block like def my_varStage_2 as env.my_var = "${var_1}/${var_2}" and use in Stage_3 as ${env.my_var}but none of approaches allows to get my_var value from Stage_2... So how should I fix the pipeline?
Jenkins passes environment variables to scripts "by value", not "by reference", conceptually speaking. If you want to persist any state between sh steps (doesn't matter inside the same stage or different stages) you have two options:
Pick your poison.