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

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

Resolution

The best way to accomplish this is through some simple scripted Pipeline at the start of your Jenkinsfile:

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.

JENKINS-43353 tracks a feature request to make this a core feature of Pipeline, but the above workaround is the most efficient solution available currently.

References

Have more questions?

0 Comments

Please sign in to leave a comment.