Can I check if an environment variable exists or not in the Jenkinsfile

I am running a multibranch pipeline for my project.

The behavior of the Jenkins file should change according to the trigger. There are two events that trigger the pipeline 1. Click event 2. Request Pull.

I am trying to check the environment variable "CHANGE_ID" ("CHANGE_ID" will be available only for a Pull request). Link .

So, if the pipeline triggers using the Push and If event, checking the CHANGE_ID variable, it throws an exception (the code works fine if the pipeline starts using the Pull request).

Code:

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

Mistake:

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 variable CHANGE_ID or not in the Jenkins file?

+6
2

:

 if (env.CHANGE_ID) {
 ...

doc

, , : env.PATH env.BUILD_ID. , Pipeline.

+13

:

pipeline {
    // ...
    stages {
        // ...
        stage('Build') {
            when {
                allOf {
                    expression { env.CHANGE_ID != null }
                    expression { env.CHANGE_TARGET != null }
                }
            }
            steps {
                echo "Building PR #${env.CHANGE_ID}"
            }
        }
    }
}

, PR:

when { expression { env.CHANGE_ID == null } }
+2

All Articles