How can I abort a running Pipeline build if a new one is started?

Article ID:360034881371
1 minute readKnowledge base

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.

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.

This article is part of our Knowledge Base and is provided for guidance-based purposes only. The solutions or workarounds described here are not officially supported by CloudBees and may not be applicable in all environments. Use at your own discretion, and test changes in a safe environment before applying them to production systems.