Created
October 13, 2023 06:36
-
-
Save JoSSte/731c0f598d40e70163aa814b82bd7973 to your computer and use it in GitHub Desktop.
Jenkins failed/aborted jobs cleanup
This file contains 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
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