Skip to content

Instantly share code, notes, and snippets.

@bgaillard
Last active July 12, 2021 00:55
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bgaillard/d1f4e71cb2404c32b36e1ee7dea68ccf to your computer and use it in GitHub Desktop.
Save bgaillard/d1f4e71cb2404c32b36e1ee7dea68ccf to your computer and use it in GitHub Desktop.
Jenkins - Cleanup old builds
import com.cloudbees.hudson.plugins.folder.*;
/**
* Utility function used to delete old builds associated to a Jenkins project.
*
* @param item the current Jenkins item to process, this can be a Folder or a Project
* @param numberOfBuildsToKeep the total number of builds to keep. Please note that one more build could be
* kept if the firt "numberOfBuildsToKeep" builds are all in failed state.
*/
def deleteOldBuilds(item, numberOfBuildsToKeep) {
// If the item is a project then remove its old builds
if(item instanceof Project) {
def i = 1
def numberOfSuccessfulBuildsKept = 0
println ""
println "Begin deletion of old builds for project \"" + item.getName() + "\"..."
for (build in item.getBuilds()) {
if(i++ > numberOfBuildsToKeep) {
if(item.getBuildStatusIconClassName() == "icon-blue" && numberOfSuccessfulBuildsKept == 0) {
println "Keep " + build
} else {
println "Delete " + build
build.delete()
}
} else if(item.getBuildStatusIconClassName() == "icon-blue") {
numberOfSuccessfulBuildsKept++;
}
}
}
// If the item is a folder then execute recursive call
else if(item instanceof Folder) {
for (subItem in item.items) {
deleteOldBuilds(subItem, numberOfBuildsToKeep);
}
}
}
// For each root item
for (item in Jenkins.instance.items) {
deleteOldBuilds(item, 3);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment