Can I check if Environment variable exist or not in Jenkinsfile
Asked Answered
K

4

60

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?

Kirbykirch answered 18/8, 2017 at 14:3 Comment(0)
A
89

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.

Am‚lie answered 18/8, 2017 at 15:23 Comment(6)
@Kirbykirch Glad it helps, you can accept my answer (*≧∪≦)Am‚lie
If not working the script tag can be used: "script { if(env.CHANGE_ID){"Kutaisi
for completeness, the value of env.DOES_NOT_EXIST is nullMyrna
I have one additional question what in case when we have i.e. 10 or more variables to check and all of them are named starting from the same word (BUILD_ID, BUILD_NUMBER, BUILD_DATE,... etc). It is possible to use some kind of sentence as below?: if (env.BUILD_*) { ...Chavers
This does NOT check if the value exists, but rather a check if the string is not empty. if (env.CHANGE_ID != null) is the correct check.Batavia
So I have pipeline{ environment { REQUEST_NAME = abc } ....}, in my post { always { .... } section I tried to add if(env.REQUEST_NAME).... and got an error Expected a step @ line 490, column 13. I have plenty of other actions in this area that are not 'step's like echo, archiveArtifacts, calls to python scripts, etcKorea
A
47

This is how it would look like for a declarative pipeline:

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

To run a stage only when not building a PR:

when { expression { env.CHANGE_ID == null } }
Austroasiatic answered 2/2, 2018 at 11:53 Comment(2)
Yes, thank you! Using changeRequest did not always do what I expected. Using the env vars is what I needed.Marozas
The use of 'env.' is not needed for declarative pipelines. The variable can be tested directly; e.g. CHANGE_ID != nullParaplegia
M
8

You can also use the changeRequest() function in the when clause to check for PR:

when {
   anyOf {
      changeRequest()    // if pull request
      branch 'master'
      branch 'release/*'
   }
}
Milne answered 24/12, 2019 at 9:14 Comment(0)
I
1

some things to know (or at least to guess) upfront:

  • Jenkins Groovy runtime uses the env object(?) for managing current environment variables - this means its not guaranteed that any env member will also be present within the "binding" system
  • certain members, such as WORKSPACE might only be there when running in a node/agent/ws covered context.
  • some/all(?) members are same time present as env.<name> and <name>
  • trying to access a non-existing member for env.<name> will result in null whilst for the same case accessing <name> will raise a fault.
  • there are special members that will fail locating them via binding or similar class systems.

thus i would recommend to realize code that looks something like that:

if (env.WORKSPACE != null) {
    println "WORKSPACE=${WORKSPACE}"  // or ${env.WORKSPACE}
    // checking for an empty string value is now a simple story.
} else {
    println "WORKSPACE is null"
}
Iquitos answered 14/4, 2023 at 15:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.