Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save soerenmartius/66dc04e153c12c6e2b39bbfc76fcd53c to your computer and use it in GitHub Desktop.
Save soerenmartius/66dc04e153c12c6e2b39bbfc76fcd53c to your computer and use it in GitHub Desktop.
jenkins kill all jobs for a specific project
import hudson.model.FreeStyleBuild
import hudson.model.Result
import hudson.model.Run
import jenkins.model.Jenkins
import org.jenkinsci.plugins.workflow.job.WorkflowRun
import org.jenkinsci.plugins.workflow.support.steps.StageStepExecution
if(!binding.hasVariable('dryRun')) {
dryRun = true
}
if(!binding.hasVariable('projectFullName')) {
projectFullName = 'project/full/name'
}
//type check user defined parameters/bindings
if(!(dryRun instanceof Boolean)) {
throw new Exception('PARAMETER ERROR: dryRun must be a boolean.')
}
if(!(projectFullName instanceof String)) {
throw new Exception('PARAMETER ERROR: projectFullName must be a string.')
}
Jenkins.instance.getItemByFullName(projectFullName).builds.each { Run item ->
if(item.isBuilding()) {
if(item instanceof WorkflowRun) {
WorkflowRun run = (WorkflowRun) item
if(!dryRun) {
//hard kill
run.doKill()
//release pipeline concurrency locks
StageStepExecution.exit(run)
}
println "Killed ${run}"
} else if(item instanceof FreeStyleBuild) {
FreeStyleBuild run = (FreeStyleBuild) item
if(!dryRun) {
run.executor.interrupt(Result.ABORTED)
}
println "Killed ${run}"
} else {
println "WARNING: Don't know how to handle ${item.class}"
}
}
}.each{ build ->
if(build.isBuilding()) {
build.doKill()
println "killed ${build}"
}
}
//null so no result shows up
null
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment