Search code examples
jenkinsjenkins-pipelinemultibranch-pipeline

How can I configure Jenkins multibranch pipelines to use option with different args for branches & pull requests in a single Jenkinsfile?


i am working on declarative jenkins multibranch pipelines and i would like to use

  • options { disableConcurrentBuilds(abortPrevious: false) } when building branches
  • and options { disableConcurrentBuilds(abortPrevious: true) } when building pull requests.

options

disableConcurrentBuilds

Disallow concurrent executions of the Pipeline. Can be useful for preventing simultaneous accesses to shared resources, etc. For example: options { disableConcurrentBuilds() } to queue a build when there’s already an executing build of the Pipeline, or options { disableConcurrentBuilds(abortPrevious: true) } to abort the running one and start the new build.

Is it possible to configure Jenkins multibranch pipelines to use different arguments for disableConcurrentBuilds() options based on branch type in a single Jenkinsfile?


like it is possible in azure pipelines with batch and autoCancel:

trigger:
  batch: true #waits until the run is completed, then starts another run
  branches:
    include:
      - main
pr:
  autoCancel: true #cancel in-progress runs for the same PR Defaults to true
  branches:
    include:
      - '*'

Solution

  • When building pull requests, Jenkins defines an environment variable named CHANGE_ID. You can use it to set the boolean parameter:

    options { 
        disableConcurrentBuilds(abortPrevious: env.CHANGE_ID ? true : false) 
    }