一尘不染

如何在声明性Jenkins管道的各个阶段之间传递变量?

jenkins

如何在声明式管道的各个阶段之间传递变量?

在脚本化管道中,我收集的过程是写入一个临时文件,然后将该文件读入一个变量。

如何在声明管道中执行此操作?

例如,我想基于shell动作创建的变量来触发其他作业的构建。

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})]
    }
}

阅读 557

收藏
2020-07-25

共1个答案

一尘不染

如果要使用文件(由于脚本是生成所需值的东西),则可以readFile如下所示使用。如果没有,请使用如下所示shscript选项:

// 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}"
      }
    }
  }
}
2020-07-25