How-to: Cancel all Jenkins builds

If you have a bunch of Jenkins builds running and want to cancel them all, just use this Groovy script:

//-----------------------------------------------------------------------------
// TOO1 (04/06/17): Created initial script to cancel all running/queued builds
//-----------------------------------------------------------------------------
//
// Add this script into the Jenkins Build Step "System Groovy Script"

import jenkins.model.Jenkins
import hudson.model.AbstractProject

def thisBuild = build

println "//-----------------------------------------------------------------------------"
println "// (1) Canceling all builds pending in the build queue"
println "//-----------------------------------------------------------------------------"
println ""
def q = Jenkins.instance.queue
def numCanceledInQ = 0
q.items.each { q.cancel(it.task); ++numCanceledInQ }

println "Canceled (" + numCanceledInQ + ") builds in the queue."
println ""


println "//-----------------------------------------------------------------------------"
println "// (2) Canceling all currently running builds"
println "//-----------------------------------------------------------------------------"
println ""
def numCanceledInBuild = 0
Jenkins.instance.getAllItems(AbstractProject.class).each {job ->
  for (build in job.builds) {
    if (!build.isBuilding())
      // don't need to cancel builds that are not building
      continue;
    else if (build.getFullDisplayName().equals(thisBuild.getFullDisplayName()))
      // don't cancel this job
      continue;
    else
      println "Canceling " + build.getFullDisplayName();
      build.doStop();
      ++numCanceledInBuild;
  }
}


println "Canceled (" + numCanceledInBuild + ") builds that were currently running."
println ""
println "//-----------------------------------------------------------------------------"

return;

I like to create a dedicated Jenkins Job titled "Cancel All Builds" that executes this script. This way, I'm able to retain a history of cancellations.

Explore More