Jenkins delete builds older than latest 20 builds for all jobs
You can use the Jenkins Script Console to iterate through all jobs, get a list of the N most recent and perform some action on the others.
import jenkins.model.Jenkinsimport hudson.model.JobMAX_BUILDS = 20for (job in Jenkins.instance.items) { println job.name def recent = job.builds.limit(MAX_BUILDS) for (build in job.builds) { if (!recent.contains(build)) { println "Preparing to delete: " + build // build.delete() } }}
The Jenkins Script Console is a great tool for administrative maintenance like this and there's often an existing script that does something similar to what you want.
I got an issue No such property: builds for class: com.cloudbees.hudson.plugins.folder.Folder
on Folders Plugin 6.6 while running @Dave Bacher's script
Alter it to use functional api
import jenkins.model.Jenkinsimport hudson.model.JobMAX_BUILDS = 5Jenkins.instance.getAllItems(Job.class).each { job -> println job.name def recent = job.builds.limit(MAX_BUILDS) for (build in job.builds) { if (!recent.contains(build)) { println "Preparing to delete: " + build build.delete() } }}
There are lots of ways to do this
Personally I would use the 'discard old builds' in the job config
If you have lots of jobs you could use the CLI to step through all the jobs to add it
Alternatively there is the configuration slicing plugin which will also do this for you on a large scale