Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jenkins workflow environment variables causing a failure

For this very simple workflow:

env.FOO = 42
node {
  sh "echo $FOO"
}

I get the following error:

Running: End of Workflow
groovy.lang.MissingPropertyException: No such property: FOO for class: WorkflowScript

How do I access environment variables in workflow shell steps?

like image 335
Michael Neale Avatar asked Dec 01 '15 06:12

Michael Neale


People also ask

How does Jenkins pipeline override environment variables?

Overriding Environment VariableAny variable defined in the pipeline environment block can be overridden in the local stage environment. We can check this by overriding the USER_ID to 32, and this variable will override the variable from the pipeline level environment.

Can Jenkins use system environment variables?

Environment variables are global key-value pairs Jenkins can access and inject into a project. Use Jenkins environment variables to avoid having to code the same values for each project. Other benefits of using Jenkins environment variables include improved security.

How do you set an environment variable in Jenkins pipeline?

We can set environment variables globally by declaring them in the environment directive of our Jenkinsfile. This approach of defining the variables in the Jenkins file is useful for instructing the scripts; for example, a Make file.


2 Answers

I had an issue where I needed to mix interpolation. Where part of the script is interpolated before, and part of the script is interpolated during. The trick to to escape the variable(s) you want interpolated during the run with a backslash:

def FOO = 42

node {
  sh """
    BAR = "hello $FOO"
    echo \$BAR
  """
}

So $FOO is expanded before the script runs, and \$BAR is expanded during the script run.

like image 148
Dennis Hoer Avatar answered Oct 21 '22 23:10

Dennis Hoer


The reason is that with double quotes the string interpolation of Groovy kicks in and looks for a workflow scoped variable of FOO.

To fix use single quotes:

sh 'echo $FOO'

Note also you can use workflow variables in scripts with double quotes:

def FOO = 43

node {
  sh "echo $FOO"
}

This will expand the value of $FOO before the script is run.

like image 33
Michael Neale Avatar answered Oct 22 '22 00:10

Michael Neale