Search code examples
jenkinsjenkins-workflow

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?


Solution

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