Search code examples
jenkinsjenkins-pipelinemultibranch-pipeline

How to disable triggers from branch indexing but still allow SCM triggering in multibranch jobs


When using a Jenkins Multibranch Pipeline Job if you choose Suppress Automatic SCM trigger in the job it will stop the job from building after indexing branches (great functionality).

However for some reason this ALSO will kill the ability to trigger the build from SCM events!

Is there any way to stop builds from triggering after branch discovery (branch indexing) but still build normally by SCM events?


Solution

  • You can always add logic to your pipeline to abort on branch indexing causes. For example:

      boolean isBranchIndexingCause() {
        def isBranchIndexing = false
        if (!currentBuild.rawBuild) {
          return true
        }
    
        currentBuild.rawBuild.getCauses().each { cause ->
          if (cause instanceof jenkins.branch.BranchIndexingCause) {
            isBranchIndexing = true
          }
        }
        return isBranchIndexing
      }
    

    Adjust the logic to suit your use-case.

    EDIT: The Pipeline Syntax > Global Variables Reference embedded within the Jenkins UI (e.g.: <jenkins url>/job/<pipeline job name>/pipeline-syntax/globals) has information about the currentBuild global variable, which lead to some javadocs:

    The currentBuild variable, which is of type RunWrapper, may be used to refer to the currently running build. It has the following readable properties:

    ...

    rawBuild:

    a hudson.model.Run with further APIs, only for trusted libraries or administrator-approved scripts outside the sandbox; the value will not be Serializable so you may only access it inside a method marked @NonCPS

    ...

    See also: jenkins.branch.BranchIndexingCause