Issue
-
You have a Pipeline or Pipeline Multibranch job, and you want the running job to be aborted automatically if a new run is started. This can be useful if a new commit is made to the same branch of a project, and therefore you have no need to continue building the previous commit.
Environment
-
CloudBees CI (CloudBees Core) on modern cloud platforms - Managed controller
-
CloudBees CI (CloudBees Core) on modern cloud platforms - Operations Center
-
CloudBees CI (CloudBees Core) on traditional platforms - Client controller
-
CloudBees CI (CloudBees Core) on traditional platforms - Operations Center
-
CloudBees Jenkins Enterprise
-
CloudBees Jenkins Enterprise - Managed controller
-
CloudBees Jenkins Enterprise - Operations center
Resolution
Since version 2.42 of the Pipeline: Job plugin, the recommended approach is to use the option disableConcurrentBuilds(abortPrevious: true)
:
Declarative Pipeline:
pipeline { options { disableConcurrentBuilds(abortPrevious: true) } [...] }
Scripted Pipeline:
node { properties([disableConcurrentBuilds(abortPrevious: true)]) [...] }
Pipeline: Job version earlier than 2.42
In earlier versions, this can be accomplished through some simple scripted Pipeline at the start of the Jenkinsfile / Pipeline script:
def buildNumber = env.BUILD_NUMBER as int if (buildNumber > 1) milestone(buildNumber - 1) milestone(buildNumber)
The outcome of this is that build #1 will create milestone1
in the project. While build #1 is running, if build #2 is started, it will create milestone1
and milestone2
in the project. Build #2 will immediately pass milestone1
and will therefore cause Build #1 to abort.