I'm hoping to add a conditional stage to my Jenkinsfile that runs depending on how the build was triggered. Currently we are set up such that builds are either triggered by:
- changes to our git repo that are picked up on branch indexing
- a user manually triggering the build using the 'build now' button in the UI.
Is there any way to run different pipeline steps depending on which of these actions triggered the build?
In Jenkins Pipeline without
currentBuild.rawBuild
access the build causes could be retrieved in the following way:The following code should works to determine if a user has started the pipeline or a timer/other trigger:
I think that the answers here are incomplete and do not provide an actual ready to use answer. Here's my code to get it working:
When started by user:
When started by timer:
Note: the NonCPS decorator is needed because otherwise the next non-script step will throw.
The ability to get causes for a workflow run was released in version 2.22 (2018 Nov 02) to the Pipeline Supporting APIs Plugin. The feature was requested in JENKINS-41272.
A couple methods were added to the
currentBuild
global variable with that release:And an example from me submitting:
And the output:
NOTE
There appears to be an issue with the
currentBuild.getBuildCauses(type)
when thetype
is a type ofCause
contributed by a plugin. For example,currentBuild.getBuildCauses('org.jenkinsci.plugins.workflow.cps.replay.ReplayCause')
fails with ajava.lang.ClassNotFoundException
. This was reported in JENKINS-54673 for the2.22
version of the Pipeline: Supporting APIs (workflow-support
) plugin. It is reportedly fixed in the2.24
version.Assuming the two different build causes are "timer" and "push" (to a git repo), you can add the following stage to your Jenkinsfile (in a declarative Jenkins pipeline) to make use of
getBuildCauses()
:Then I can decide whether to perform certain stages conditionally (depending on the build cause). For example, pulling a docker base image and inspecting for changes in system libraries (likely security updates) should be done periodically, regardless of whether there was a source code change or not.
We can use "BUILD_CAUSE" variable for getting the information about who initiated the run
for [jenkins-pipeline] you may use
(see github.com/jenkinsci/pipeline-examples/blob/master/… for more details)