Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access a Groovy variable from within shell step in Jenkins pipeline

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.

like image 367
Dirk Avatar asked Oct 11 '16 16:10

Dirk


People also ask

How do I display a variable in Groovy?

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.


1 Answers

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

sh "echo $some_var" 
like image 61
Dave Bacher Avatar answered Oct 03 '22 06:10

Dave Bacher