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

后端 未结 3 1798
情书的邮戳
情书的邮戳 2020-12-01 01:01

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

3条回答
  •  猫巷女王i
    2020-12-01 01:31

    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 global variable, myVar.
    // A local, def myVar = 'initial_value', didn't work for me.
    // 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.
    myVar = 'initial_value'
    
    pipeline {
      agent { label 'docker' }
      stages {
        stage('one') {
          steps {
            echo "${myVar}" // prints '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()
    
              // OPTION 2: set variable by grabbing output from script
              myVar = sh(script: 'echo hotness', returnStdout: true).trim()
            }
            echo "${myVar}" // prints 'hotness'
          }
        }
        stage('two') {
          steps {
            echo "${myVar}" // prints 'hotness'
          }
        }
        // this stage is skipped due to the when expression, so nothing is printed
        stage('three') {
          when {
            expression { myVar != 'hotness' }
          }
          steps {
            echo "three: ${myVar}"
          }
        }
      }
    }
    

提交回复
热议问题