在Jenkins管道的Shell步骤中访问Groovy变量

使用Jenkins

2.x中的Pipeline插件,如何从一个sh步骤中访问在阶段或节点级别某个位置定义的Groovy变量?

简单的例子:

node {

stage('Test Stage') {

some_var = 'Hello World' // this is Groovy

echo some_var // printing via Groovy works

sh 'echo $some_var' // printing in shell does not work

}

}

在Jenkins输出页面上给出以下内容:

[Pipeline] {

[Pipeline] stage

[Pipeline] { (Test Stage)

[Pipeline] echo

Hello World

[Pipeline] sh

[test] Running shell script

+ echo

[Pipeline] }

[Pipeline] // stage

[Pipeline] }

[Pipeline] // node

[Pipeline] End of Pipeline

Finished: SUCCESS

可以看到,echo在该sh步骤中将打印一个空字符串。

解决方法是通过以下方式在环境范围内定义变量

env.some_var = 'Hello World'

并通过打印

sh 'echo ${env.some_var}'

但是,这种滥用会破坏此任务的环境范围。

回答:

要使用可模板化的字符串(将变量替换为字符串),请使用双引号。

sh "echo $some_var"

以上是 在Jenkins管道的Shell步骤中访问Groovy变量 的全部内容, 来源链接: utcz.com/qa/417306.html

回到顶部