Jenkins Pipeline define and set variables

Viewed 8313

I am using branch name to pass it into build script. $(env.BRANCH_NAME).

I would like to manipulate the value before using it. For example in case we build from trunk I want suffix for the build output be empty but in case of branch I want it to be -branch name.

currently I am doing it by defining environment section.

environment {
    OUTPUT_NAME_SUFFIX = ($(env.BRANCH_NAME) == 'trunk') ? '': $(env.BRANCH_NAME)
}

I am getting this error:

WorkflowScript: 4: Environment variable values must either be single quoted, double quoted, or function calls. @ line 4, column 62.
   (env.BRANCH_NAME) == 'trunk') ? '': $(en
                                 ^

What the best way to define variables and eval their values in scope of pipeline.

TIA

2 Answers

You can use string interpolation to evaluate the expression:

environment {
    OUTPUT_NAME_SUFFIX = "${env.BRANCH_NAME == 'trunk' ? '': env.BRANCH_NAME}"
}

This will fix the error you're getting, however pipeline does not allow you to have environment variables that are of 0 length, aka empty string (JENKINS-43632).

That means that setting OUTPUT_NAME_SUFFIX to '' is like unseting it. You might want to precalculate the whole name of your output, so that your env variable is never an empty string.

I have solved it by adding following code. So far had no issues with empty strings.

stage('Set Environmnet'){
            steps {
                script {        
                    if(BRANCH_NAME == 'trunk'){
                        env.OUTPUT_NAME_SUFFIX = ''
                    }else if (BRANCH_NAME.startsWith("branches")){
                        env.OUTPUT_NAME_SUFFIX = "-" + BRANCH_NAME.substring(BRANCH_NAME.lastIndexOf("/")+1)
                    }else{
                        env.OUTPUT_NAME_SUFFIX = ''
                    }
                }
            }

        }
Related