Skip to content

Instantly share code, notes, and snippets.

@vvucetic
Last active March 14, 2019 14:13
Show Gist options
  • Select an option

  • Save vvucetic/8d8bceb4faf45c7a8a19444dca216c7f to your computer and use it in GitHub Desktop.

Select an option

Save vvucetic/8d8bceb4faf45c7a8a19444dca216c7f to your computer and use it in GitHub Desktop.
Stop previously running Jenkins pipeline jobs
@NonCPS
def cancelPreviousBuilds() {
def jobName = env.JOB_NAME
def buildNumber = env.BUILD_NUMBER.toInteger()
/* Get job name */
def currentJob = Jenkins.instance.getItemByFullName(jobName)
/* Iterating over the builds for specific job */
for (def build : currentJob.builds) {
def exec = build.getExecutor()
/* If there is a build that is currently running and it's not current build */
if (build.isBuilding() && build.number.toInteger() != buildNumber && exec != null) {
/* Then stop it */
exec.interrupt(
Result.ABORTED,
new CauseOfInterruption.UserInterruption("Aborted by #${currentBuild.number}")
)
println("Aborted previously running build #${build.number}")
}
}
}
pipeline {
agent any
stages {
stage('Init') {
agent { label 'master' }
steps {
script {
cancelPreviousBuilds()
}
}
}
stage('Test') {
agent { label 'agent' }
steps {
//...
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment