Last active
April 6, 2020 10:10
-
-
Save aleskiontherun/c311906f55b94c384107ff65823f5082 to your computer and use it in GitHub Desktop.
Groovy script to delete old disabled Jenkins jobs.
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
/*** BEGIN META {"name" : "Bulk Delete Jobs", | |
"comment" : "Delete jobs disabled and where last build is older than specified param", | |
"parameters" : [ 'dryRun', 'numberOfDays', 'excludeRegexp' ], | |
"core": "2.0", | |
"authors" : [{ name : "Benjamin Francisoud" }, { name : "Aleksei Vesnin" }]} END META**/ | |
import jenkins.model.* | |
import java.util.regex.Pattern | |
dryRun = false | |
numberOfDays = 20 | |
excludeRegexp = null | |
jenkins = Jenkins.instance | |
dryRun = dryRun.toBoolean() | |
println "Dry mode: $dryRun" | |
numberOfDays = numberOfDays.toInteger() ?: 365 | |
println "numberOfDays: $numberOfDays" | |
excludeRegexp = excludeRegexp ?: '(Template).*' | |
println "excludeRegexp: ${excludeRegexp}" | |
pattern = Pattern.compile(excludeRegexp) | |
count = 0 | |
now = new Date() | |
xDaysAgo = new Date(((long) now.time - (1000L * 60 * 60 * 24 * numberOfDays))) | |
println "\nNow: ${now}" | |
println "X days ago: ${xDaysAgo}\n" | |
def getJobs(items, prefix = '') { | |
items.each { | |
if (it instanceof com.cloudbees.hudson.plugins.folder.Folder) { | |
getJobs(it.items, prefix + it.name + '/') | |
} else if (it instanceof hudson.model.AbstractProject) { | |
def jobName = prefix + it.name | |
if (it.disabled == true && (it.lastSuccessfulBuild?.time?.before(xDaysAgo) || it.lastSuccessfulBuild == null) && !pattern.matcher(jobName).matches()) { | |
if (it.firstBuild?.time?.after(xDaysAgo)) { | |
println "No successful builds for ${jobName}, but we won't disable it yet as it's less than ${numberOfDays} days old; first build was at ${it.firstBuild?.time}" | |
} else { | |
println "Deleting ${jobName.padRight(52, ' _')} at ${now}. lastSuccessfulBuild ${it.lastSuccessfulBuild?.time}" | |
if (!dryRun) { | |
it.delete() | |
} | |
count++ | |
} | |
} | |
} | |
} | |
} | |
getJobs(jenkins.items) | |
println "\nDeleted ${count} jobs.\n" | |
return |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment