Access a Groovy variable from within shell step in

2019-01-11 23:30发布

问题:

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"