Reputation: 21
So, I start my pipeline script with this piece of code:
node {
if (env.JOB_NAME != 'Company/project/develop' && env.JOB_NAME != 'Company/project/master'){
def jobName = env.JOB_NAME
def job = Jenkins.instance.getItemByFullName(jobName)
for (build in job.builds) {
if (build.isBuilding() && build != job.builds.first()) {
println '*' * 30
println 'All previous builds for this job have been aborted!'
println '*' * 30
build.doStop()
}}
}
}
And it works perfectly. It stops all previous builds for the same job name. The point of this is to optimize Jenkins when developers are pushing too much code, but latest push is only important one. Master and develop branches are excluded from this rule.
I would like to expand this a little bit, by adding interruption cause. I would like to print into stopped build for example: "This job has been stop because is obsolete..."
I have tried a lot of things posted on stackoverflow, but I didn't succeed.
Thanks
Upvotes: 0
Views: 1651
Reputation: 6205
Here is my implementation of similar function. It will abort previous running build, and show cause "Aborted by newer build #123"
import hudson.model.Result
import hudson.model.Run
import jenkins.model.CauseOfInterruption.UserInterruption
Run previousBuild = currentBuild.rawBuild.getPreviousBuildInProgress()
while (previousBuild != null) {
if (previousBuild.isInProgress()) {
def executor = previousBuild.getExecutor()
if (executor != null) {
echo ">> Aborting older build #${previousBuild.number}"
executor.interrupt(Result.ABORTED, new UserInterruption("Aborted by newer build #${currentBuild.number}"))
}
}
previousBuild = previousBuild.getPreviousBuildInProgress()
}
Upvotes: 2