Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use groovy to populate an env variable in a declarative jenkins pipeline

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.

like image 612
user3124206 Avatar asked Jul 25 '18 16:07

user3124206


1 Answers

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]}"
}
like image 199
Szymon Stepniak Avatar answered Sep 19 '22 08:09

Szymon Stepniak