Access a Groovy variable from within shell step in Jenkins pipeline

心已入冬 提交于 2019-11-26 23:00:47

问题


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?

Simple example:

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
    }
}

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

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

A work-around would be to define the variable in the environment scope via

env.some_var = 'Hello World'

and print it via

sh 'echo ${env.some_var}'

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


回答1:


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

sh "echo $some_var"



回答2:


I am adding the comment from @Pedro as an answer because I think it is important.

For sh env vars we must use

sh "echo \$some_var" 



回答3:


In order to Pass groovy parameters into bash scripts in Jenkins pipelines - Use this post here



来源:https://stackoverflow.com/questions/39982414/access-a-groovy-variable-from-within-shell-step-in-jenkins-pipeline

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!