Search code examples
jenkinspipelinejenkins-declarative-pipeline

How to share variables between stages in declarative pipeline


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

  • define variable outside the pipeline block like def my_var
  • define it in Stage_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?


Solution

  • 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:

    1. Pass the state information back to Jenkins (serialize to stdout and capture it in Jenkins), but you sacrifice declarative purity
    2. Save it in some file in the workspace, which is not such a good idea generally speaking, but acceptable in very simple cases

    Pick your poison.