从 Jenkins 管道的 shell 步骤中访问 Groovy 变量 [英] Access a Groovy variable from within shell step in Jenkins pipeline

查看:56
本文介绍了从 Jenkins 管道的 shell 步骤中访问 Groovy 变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 Jenkins 2.x 中的管道插件,我如何访问在 sh 步骤中的某个阶段或节点级别的某处定义的 Groovy 变量?

Using the Pipeline plugin in Jenkins 2.x, how can I access a Groovy variable that is defined somewhere at stage- or node-level from within a 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 输出页面上提供以下内容:

gives the following on the Jenkins output page:

[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

如我们所见,sh 步骤中的 echo 打印出一个空字符串.

As one can see, echo in the sh step prints an empty string.

一种解决方法是通过

env.some_var = 'Hello World'

并通过

sh 'echo ${env.some_var}'

然而,这种滥用此任务的环境范围.

However, this kind of abuses the environmental scope for this task.

推荐答案

要使用可模板化的字符串,其中变量被替换为字符串,请使用双引号.

To use a templatable string, where variables are substituted into a string, use double quotes.

sh "echo $some_var"

这篇关于从 Jenkins 管道的 shell 步骤中访问 Groovy 变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆