Can I check if Environment variable exist or not in Jenkinsfile

kishs1991 picture kishs1991 · Aug 18, 2017 · Viewed 57.4k times · Source

I am running Multibranch pipeline for my project.

The behaviour of Jenkinsfile should change according to the trigger. There are two events that triggeres the pipeline 1. Push event 2. Pull Request.

I am trying to check Environment variable 'CHANGE_ID' ('CHANGE_ID' will be available for Pull Request only).Reference .

So if pipeline is triggred by Push event and If check the 'CHANGE_ID' variable it throws exception (code works fine if pipeline gets triggered by Pull Request).

Code:

stage('groovyTest'){
    node('mynode1') {
        if (CHANGE_ID!=NULL){
            echo "This is Pull request"
        }else{
            echo "This is Push request"
        }
    }
}

Error:

groovy.lang.MissingPropertyException: No such property: CHANGE_ID for class: groovy.lang.Binding
    at groovy.lang.Binding.getVariable(Binding.java:63)
    at org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.SandboxInterceptor.onGetProperty(SandboxInterceptor.java:224)
    at org.kohsuke.groovy.sandbox.impl.Checker$4.call(Checker.java:241)
    at org.kohsuke.groovy.sandbox.impl.Checker.checkedGetProperty(Checker.java:238)
    at org.kohsuke.groovy.sandbox.impl.Checker.checkedGetProperty(Checker.java:221)
    at org.kohsuke.groovy.sandbox.impl.Checker.checkedGetProperty(Checker.java:221)
    at com.cloudbees.groovy.cps.sandbox.SandboxInvoker.getProperty(SandboxInvoker.java:28)
    at com.cloudbees.groovy.cps.impl.PropertyAccessBlock.rawGet(PropertyAccessBlock.java:20)
    at WorkflowScript.run(WorkflowScript:5)
    at ___cps.transform___(Native Method)

How can I check the 'CHANGE_ID' variable exist or not in Jenkinsfile?

Answer

aristotll picture aristotll · Aug 18, 2017

You may check it before use it:

 if (env.CHANGE_ID) {
 ...

From the doc

Environment variables accessible from Scripted Pipeline, for example: env.PATH or env.BUILD_ID. Consult the built-in Global Variable Reference for a complete, and up to date, list of environment variables available in Pipeline.