Last active
March 14, 2019 14:13
-
-
Save vvucetic/8d8bceb4faf45c7a8a19444dca216c7f to your computer and use it in GitHub Desktop.
Stop previously running Jenkins pipeline jobs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| @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