2
votes

I've trouble setting an environment variable for a container in an Jenkins pipeline. It seems, that "withEnv" does not work nicely with machines without bash.

Can you confirm that? I cannot find an official statement ;-)

When I run the following snippet on the Jenkins slave it works. But when it is executed in a docker container without BASH "$test" isn't set.

 withEnv(["test='asd'"]){
      sh 'echo $test'
 }

https://jenkins.io/doc/pipeline/steps/workflow-basic-steps/#code-withenv-code-set-environment-variables

2
Is "test" a groovy variable or a bash variable?Itai Ganot
test should become a bash variable (in the block).Sebastian Woinar
It is possible that Jenkins node passes variables to sub-shell where is runs docker, but docker does not pass environment variables to its own subshell; try this: stackoverflow.com/a/30494145/1388202sterdun

2 Answers

11
votes

If I'm not mistaken, I believe the variable is not set correctly.

Try this:

withEnv(["test=asd"]){
      sh "echo \$test"
 }

Within a Jenkins pipeline:

$var = Groovy parameter
\$var (within a sh closure) = Bash parameter
${var} = also refers to Groovy parameter

In order to insert a groovy variable into a bash variable:

sh ("VAR=${GROOVY_VAR}")

Using a bash variable inside a sh closure:

sh (" echo \$BASH_VAR")
0
votes

We have to use single quote when using withEnv in Jenkins.

withEnv(['test=asd']){
  sh "echo \$test"

}

Because, the variable expansion is being done by the Bourne shell, not Jenkins. (Quoting from documentation)

Find more info here: https://jenkins.io/doc/pipeline/steps/workflow-basic-steps/