16

Is there an environment variable in Jenkins which tells me if the build has been ran manually or automatically triggered by polling?

My pipeline works like a charm if automatically triggered, but if manually ran... it always fails, so I think I'm going to edit the pipeline to check how the build has been triggered.

Itai Ganot
  • 5,873
  • 18
  • 56
  • 99

2 Answers2

19

Unfortunately variable env.BUILD_CAUSE is not set in Pipeline builds. For pipeline jobs see following example

if ( currentBuild.rawBuild.getCauses()[0].toString().contains('UserIdCause') ){
    // do steps for manual trigger here
}

Other possible causes to compare can be found here.

Mohammad Azim
  • 2,604
  • 20
  • 21
  • 1
    If this is included in a SCM jenkinsfile, this following error occurs. Scripts not permitted to use method org.jenkinsci.plugins.workflow.support.steps.build.RunWrapper getRawBuild. This is related to https://issues.jenkins-ci.org/browse/JENKINS-28178. Do you have any suggestion for a workaround or alternative way to derive the cause? – Matt R Jul 13 '18 at 07:33
  • This article https://jenkins.io/doc/book/managing/script-approval/ explains what to do in this situation. You would need to approve the method call as an admin. – Mohammad Azim Jul 16 '18 at 08:59
  • 2
    Thanks Mohammad, I have indeed done that. However that action results in a nasty warning in Jenkins. It labels this as a security vulnerability. "Signatures already approved which may have introduced a security vulnerability (recommend clearing)". That's why I was hoping there may be a different way to derive this value. – Matt R Jul 17 '18 at 02:01
  • @MattR I believe the only other option is to wrap this in a plugin (pretty small/easy) and then just expose that as its own method to the pipeline. There is probably some plugin that extends available build info in this way too im sure. – jrich523 Aug 21 '19 at 22:16
2

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:

getBuildCauses

    Returns a JSON array of build causes for the current build

EXPERIMENTAL - MAY CHANGE getBuildCauses(String causeClass)

    Takes a string representing the fully qualified Cause class and returns a JSON array of build causes filtered by that type for the current build, or an empty JSON array if no causes of the specified type apply to the current build

See answer https://stackoverflow.com/a/53342374/5955565. I have copy-pasted it here because this question is shown first in search results (unlike How to differentiate build triggers in Jenkins Pipeline).

See also ${YOUR_JENKINS_URL}/pipeline-syntax/globals for a complete, and up to date, list of properties available on currentBuild.

Daniil
  • 96
  • 8