简体   繁体   中英

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.

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]}"
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM