#!/usr/bin/env groovy
import org.jenkinsci.plugins.workflow.job.WorkflowJob
import hudson.tasks.LogRotator
def allItems = Jenkins.instance.getAllItems(WorkflowJob)
allItems.each { job ->
newArtifactDaysToKeep = 7
newArtifactNumToKeep = 10
newDaysToKeep = 30
newNumToKeep = 100
newDiscarder = false
buildDiscarder = job.getBuildDiscarder()
if (buildDiscarder) {
if (buildDiscarder instanceof LogRotator) {
artifactDaysToKeep = buildDiscarder.getArtifactDaysToKeep()
artifactNumToKeep = buildDiscarder.getArtifactNumToKeep()
daysToKeep = buildDiscarder.getDaysToKeep()
numToKeep = buildDiscarder.getNumToKeep()
println "Existing config is: artifactDaysToKeep (${artifactDaysToKeep}) artifactNumToKeep (${artifactNumToKeep}) daysToKeep (${daysToKeep}) numToKeep (${numToKeep})"
if ((artifactDaysToKeep < 1) || (artifactNumToKeep < 1) || (daysToKeep < 1) || (numToKeep < 1)) {
newDiscarder = true
}
if (artifactDaysToKeep > 0) {
newArtifactDaysToKeep = artifactDaysToKeep
}
if (artifactNumToKeep > 0) {
newArtifactNumToKeep = artifactNumToKeep
}
if (daysToKeep > 0) {
newDaysToKeep = daysToKeep
}
if (numToKeep > 0) {
newNumToKeep = numToKeep
}
} else {
newDiscarder = true
}
} else {
newDiscarder = true
}
if (newDiscarder == true) {
println "New config is: artifactDaysToKeep (${newArtifactDaysToKeep}) artifactNumToKeep (${newArtifactNumToKeep}) daysToKeep (${newDaysToKeep}) numToKeep (${newNumToKeep})"
newBuildDiscarder = new LogRotator(newDaysToKeep, newNumToKeep, newArtifactDaysToKeep, newArtifactNumToKeep)
job.setBuildDiscarder(newBuildDiscarder)
job.save()
}
println "Running cleanup of " + job.getFullName()
job.logRotate()
}
return "completed"
To be clear that only affects orphan status (ie when an upstream repo/branch vanishes) and not build history ...
To handle build history you have to set the property in the Jenkinsfile ... or if like me you cannot control all the developers files ... run this on a regular basis