Skip to content

Instantly share code, notes, and snippets.

@jamesdmorgan
Created July 12, 2016 14:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jamesdmorgan/22309e13ac05cea789322a4b3b16cdcd to your computer and use it in GitHub Desktop.
Save jamesdmorgan/22309e13ac05cea789322a4b3b16cdcd to your computer and use it in GitHub Desktop.
import jenkins.model.*
import java.util.regex.Pattern
import java.util.Date
jenkins = Jenkins.instance
dryRun = true
numberOfDays= 60
excludeRegexp = ".*(yum|master|release|template|trunk|vm-ansible).*"
dryRun = dryRun.toBoolean()
println "Dry mode: $dryRun"
numberOfDays = numberOfDays.toInteger() ?: 365
println "numberOfDays: $numberOfDays"
excludeRegexp = excludeRegexp ?: '(Template).*'
println "excludeRegexp: ${excludeRegexp}"
pattern = Pattern.compile(excludeRegexp)
int count = 0
Date now = new Date()
Date xDaysAgo = new Date(((long)now.time-(1000L*60*60*24*numberOfDays)))
println "\nNow: ${now}"
println "X days ago: ${xDaysAgo}\n"
jobs = jenkins.items.findAll{job -> (job instanceof hudson.model.AbstractProject && (job.lastSuccessfulBuild?.time?.before(xDaysAgo) || job.lastSuccessfulBuild == null) && !pattern.matcher(job.name).matches()) }
jobs.each { job ->
if (job.firstBuild?.time?.after(xDaysAgo)) {
println "No successful builds for ${job.name}, but we won't disable it yet as it's less than ${numberOfDays} days old; first build was at ${job.firstBuild?.time}"
} else {
println "Deleting ${job.name} at ${now}. lastSuccessfulBuild ${job.lastSuccessfulBuild?.time}"
if (!dryRun) {
job.delete()
}
count++
}
}
println "\nDeleted ${count} jobs.\n"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment