小编典典

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

jenkins

使用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}'

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


阅读 553

收藏
2020-07-25

共1个答案

小编典典

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

sh "echo $some_var"
2020-07-25