从 Jenkins 管道中的 shell 步骤访问 Groovy 变量

2023-12-21

使用Jenkins 2.x 中的管道插件 https://jenkins.io/doc/book/pipeline/overview/,我如何访问在阶段或节点级别的某个位置定义的 Groovy 变量?sh step?

简单的例子:

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 in the sh步骤打印一个空字符串。

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

env.some_var = 'Hello World'

并通过打印它

sh 'echo ${env.some_var}'

然而,这种滥用该任务的环境范围。


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

sh "echo $some_var"
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

从 Jenkins 管道中的 shell 步骤访问 Groovy 变量 的相关文章

随机推荐