12

I am struggling to populate an environment variable in a Jenkinsfile using groovy

The code below fails:

pipeline {
  environment {
    PACKAGE_NAME = JOB_NAME.tokenize('/')[1]
  }
{

with the following error:

Environment variable values can only be joined together with ‘+’s

What am I doing wrong? Sorry if the question is basic, I am just starting with both groovy and pipelines.

user3124206
  • 375
  • 1
  • 7
  • 16

1 Answers1

17

Declarative pipeline is pretty strict about the values you can assign to environment variables. For instance, if you try to set PACKAGE_NAME to JOB_NAME you will get following error:

org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
WorkflowScript: 5: Environment variable values must either be single quoted, double quoted, or function calls. @ line 5, column 24.
       PACKAGE_NAME = JOB_NAME

To avoid getting errors and set PACKAGE_NAME env variable as expected you can put it into double quotes and evaluate expression inside the GString:

environment {
    PACKAGE_NAME = "${JOB_NAME.tokenize('/')[1]}"
}
Szymon Stepniak
  • 40,216
  • 10
  • 104
  • 131
  • 1
    I keep running into this, and it's mostly right, except that if your env var comes out as `null`, your custom variable will be a _string_ with content "null", and not actually a null object. As far as I can tell, i have to also specifically check if the string content is "null". – Max Cascone Feb 13 '20 at 20:55