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?
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.
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.
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.
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.
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.
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