I use Jenkins and Multibranch Pipeline. I have a job for each active git branch. New build is triggered by push in git repository. What I want is to abort running builds in
enable job parallel run for your project with Execute concurrent builds if necessary
use execute system groovy script
as a first build step:
import hudson.model.Result
import jenkins.model.CauseOfInterruption
//iterate through current project runs
build.getProject()._getRuns().iterator().each{ run ->
def exec = run.getExecutor()
//if the run is not a current build and it has executor (running) then stop it
if( run!=build && exec!=null ){
//prepare the cause of interruption
def cause = { "interrupted by build #${build.getId()}" as String } as CauseOfInterruption
exec.interrupt(Result.ABORTED, cause)
}
}
and in the interrupted job(s) there will be a log:
Build was aborted
interrupted by build #12
Finished: ABORTED
Adding to Brandon Squizzato's answer. If builds are sometimes skipped the milestone mechanism as mentioned will fail. Setting older milestones in a for-loop solves this.
Also make sure you don't have disableConcurrentBuilds in your options. Otherwise the pipeline doesn't get to the milestone step and this won't work.
def buildNumber = env.BUILD_NUMBER as int
for (int i = 1; i < buildNumber; i++)
{
milestone(i)
}
milestone(buildNumber)
Based on @daggett method. If you want to abort running build when the new push is coming and before fetch updates.
1. Enable Execute concurrent builds if necessary
2. Enable Prepare an environment for the run
3. Running bellow code in Groovy Script
or Evaluated Groovy script
import hudson.model.Result
import hudson.model.Run
import jenkins.model.CauseOfInterruption
//def abortPreviousBuilds() {
Run previousBuild = currentBuild.getPreviousBuildInProgress()
while (previousBuild != null) {
if (previousBuild.isInProgress()) {
def executor = previousBuild.getExecutor()
if (executor != null) {
println ">> Aborting older build #${previousBuild.number}"
def cause = { "interrupted by build #${currentBuild.getId()}" as String } as CauseOfInterruption
executor.interrupt(Result.ABORTED, cause)
}
}
previousBuild = previousBuild.getPreviousBuildInProgress()
}
//}