Skip to content

Instantly share code, notes, and snippets.

@JoSSte
Created October 13, 2023 06:36
Show Gist options
  • Save JoSSte/731c0f598d40e70163aa814b82bd7973 to your computer and use it in GitHub Desktop.
Save JoSSte/731c0f598d40e70163aa814b82bd7973 to your computer and use it in GitHub Desktop.
Jenkins failed/aborted jobs cleanup
import java.util.ArrayList
import hudson.model.*;
def ArrayList<String> getJobList(String pipelineName) {
def hi = hudson.model.Hudson.instance;
def item = hi.getItemByFullName(pipelineName);
def jobs = item.getAllJobs();
def arr = new ArrayList<String>();
Iterator<?> iterator = jobs.iterator();
while (iterator.hasNext()) {
def job = iterator.next();
arr.add(pipelineName + "/" + job.name);
}
return arr;
}
def deleteJobs(ArrayList<String> jobnamelist, Boolean deleteFailed = true, Boolean deleteAborted = true){
for(String jobstring in jobnamelist) {
def joblist = getJobList(jobstring)
for(String jobname in joblist) {
print("Scanning job " + jobname + " for failed and aborted builds")
def job = Jenkins.instance.getItemByFullName(jobname)
job.getBuilds().each {
//print(it.getNumber())
if((deleteFailed && it.result == Result.FAILURE) || (deleteAborted && it.result == Result.ABORTED)){
print("Deleting job " + jobname + " run # " + it.getNumber())
// Delete failed job
it.delete()
}
}
}
}
}
def jobnames = ["","",""]
pipeline {
agent {
kubernetes {
defaultContainer 'jnlp'
retries 2
}
}
options {
disableConcurrentBuilds()
}
triggers {
cron('0 22 * * 1') // run every monday at 20:00 https://crontab.guru/#0_20_*_*_1-5
}
stages {
stage ('Deleting jobs'){
steps {
script {
properties([
parameters([
booleanParam(
defaultValue: true,
description: 'Delete aborted jobs',
name: 'DELETE_ABORTED'
),
booleanParam(
defaultValue: true,
description: 'Delete failed jobs',
name: 'DELETE_FAILED'
)
])
])
}
deleteJobs(jobnames)
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment