如何在声明性 Jenkins 管道的阶段之间传递变量? [英] How do I pass variables between stages in a declarative Jenkins pipeline?
本文介绍了如何在声明性 Jenkins 管道的阶段之间传递变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在声明性管道的阶段之间传递变量?
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?
例如我想根据 shell 操作创建的变量触发不同作业的构建.
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})]
}
}
推荐答案
如果你想使用一个文件(因为脚本是生成你需要的值的东西),你可以使用 readFile
作为见下.如果没有,请使用 sh
和 script
选项,如下所示:
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}"
}
}
}
}
这篇关于如何在声明性 Jenkins 管道的阶段之间传递变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文