jenkinsgroovyjenkins-pipeline

How do I pass variables between stages in a declarative Jenkins pipeline?


How do I pass variables between stages in a declarative pipeline?

In a scripted pipeline, I gather the procedure is to write to a temporary file, then read the file into a variable.

How do I do this in a declarative pipeline?

E.g. I want to trigger a build of a different job, based on a variable created by a shell action.

stage("stage 1") {
    steps {
        sh "do_something > var.txt"
        // I want to get var.txt into VAR
    }
}
stage("stage 2") {
    steps {
        build job: "job2", parameters[string(name: "var", value: "${VAR})]
    }
}

Solution

  • If you want to use a file (since a script is the thing generating the value you need), you could use readFile as seen below. If not, use sh with the script option as seen below:

    // Define a groovy local variable, myVar.
    // A global variable without the def, like myVar = 'initial_value',
    // was required for me in older versions of jenkins. Your mileage
    // may vary. Defining the variable here maybe adds a bit of clarity,
    // showing that it is intended to be used across multiple stages.
    def myVar = 'initial_value'
    
    pipeline {
      agent { label 'docker' }
      stages {
        stage('one') {
          steps {
            echo "1.1. ${myVar}" // prints '1.1. initial_value'
            sh 'echo hotness > myfile.txt'
            script {
              // OPTION 1: set variable by reading from file.
              // FYI, trim removes leading and trailing whitespace from the string
              myVar = readFile('myfile.txt').trim()
            }
            echo "1.2. ${myVar}" // prints '1.2. hotness'
          }
        }
        stage('two') {
          steps {
            echo "2.1 ${myVar}" // prints '2.1. hotness'
            sh "echo 2.2. sh ${myVar}, Sergio" // prints '2.2. sh hotness, Sergio'
          }
        }
        // this stage is skipped due to the when expression, so nothing is printed
        stage('three') {
          when {
            expression { myVar != 'hotness' }
          }
          steps {
            echo "three: ${myVar}"
          }
        }
      }
    }