How do I prevent two pipeline jenkins jobs of the same type to run in parallel on the same node?

I do not want to allow two jobs of the same type (same repository) to run in parallel on the same node.

How can I do this using groovy inside Jenkinsfile ?


Solution 1:

The answer provided in https://stackoverflow.com/a/43963315/6839445 is deprecated.

The current method to disable concurrent builds is to set options:

options { disableConcurrentBuilds() }

Detailed description is available here: https://jenkins.io/doc/book/pipeline/syntax/#options

Solution 2:

You got at the disableConcurrentBuilds property:

properties properties: [
  ...
  disableConcurrentBuilds(),
  ...
]

Then the job would wait the older one to finish first

Solution 3:

Another way is to use the Lockable Resources plugin: https://wiki.jenkins-ci.org/display/JENKINS/Lockable+Resources+Plugin

You can define locks (mutexes) however you want and can put variables in the names. E.g. to prevent multiple jobs from using a compiler concurrently on a build node:

stage('Build') {
    lock(resource: "compiler_${env.NODE_NAME}", inversePrecedence: true) {
      milestone 1
      sh "fastlane build_release"
    }
}

So if you wanted to prevent more than one job of the same branch running concurrently per node you could do something like

stage('Build') {
    lock(resource: "lock_${env.NODE_NAME}_${env.BRANCH_NAME}", inversePrecedence: true) {
      milestone 1
      sh "fastlane build_release"
    }
}

From: https://www.quernus.co.uk/2016/10/19/lockable-resources-jenkins-pipeline-builds/