3

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

Sebastian Woinar
  • 440
  • 1
  • 8
  • 15

2 Answers2

14

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")
Itai Ganot
  • 5,873
  • 18
  • 56
  • 99
  • 2
    In general, I agree. This is the way it should work. Although, since the initial snippet uses ticks, it should work, too. But when I select a container with a very limited linux, withEnv doesn't work anymore - the variables are just not set. – Sebastian Woinar Nov 21 '16 at 16:43
  • Using Groovy variables can potentially lead to [Injection via Interpolation](https://www.jenkins.io/doc/book/pipeline/jenkinsfile/#injection-via-interpolation) vulnerabilities, so it's good you've mentioned they're different. – Bruno Mar 14 '23 at 17:52
0

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/

Nagashayan
  • 2,487
  • 2
  • 18
  • 22