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.
Variables in Groovy can be defined in two ways − using the native syntax for the data type or the next is by using the def keyword. For variable definitions it is mandatory to either provide a type name explicitly or to use "def" in replacement. This is required by the Groovy parser.
To use a templatable string, where variables are substituted into a string, use double quotes.
sh "echo $some_var"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With