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?
Via env-vars. The environment variables can be viewed on an HTML page. You have to open the page on your Jenkins controller server. The steps to view the jenkins environment variables list are : At the address bar of chrome, type ${YOUR_JENKINS_HOST}/env-vars.
Indeed just use ${env. JOB_NAME} to access a known variable. However if you need to access environment variable where name is given by another variable (dynamic access), just use env["your-env-variable"] .
In "Manage Jenkins" -> "Configure System" -> "Global Properties" -> "Environment Variables" I added "ALL_NODES_ENVVAR".
You may check it before use it:
if (env.CHANGE_ID) { ...
From the doc
Environment variables accessible from Scripted Pipeline, for example:
env.PATH
orenv.BUILD_ID
. Consult the built-in Global Variable Reference for a complete, and up to date, list of environment variables available in Pipeline.
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 } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With