I want to delete old builds for all the jobs I kept inside a folder from the script console, not from Jenkins individual job configuration to discard old builds. I want to keep only the recent 10 builds and remove the older ones. I am asking about the deletion of the old builds of a particular folder and not other jobs in another folder.
Asked
Active
Viewed 1,809 times
1
-
What is the 'script console'? – Ioannis Barakos Oct 25 '19 at 10:15
-
Jenkins script console allows one to run groovy scripts/code to automate jenkins setup e.g installing plugins, setting configuration parameters. These groovy scripts can be run either through the web ui, or event loaded as scripts using curl from command line. – Antra Verma Oct 25 '19 at 11:17
-
Possible duplicate of [Jenkins delete builds older than latest 20 builds for all jobs](https://stackoverflow.com/questions/35610053/jenkins-delete-builds-older-than-latest-20-builds-for-all-jobs) – lGSMl Oct 25 '19 at 14:17
-
I have the same req. i.e "the deletion of the old builds of a particular folder and not other jobs in another folder". Answers are usually at overall Jenkins level. – gautham p Jul 04 '22 at 08:45
1 Answers
2
The following groovy script will delete all the builds excluding the 10 most recent builds of each job configured in Jenkins.
import jenkins.model.*
import hudson.model.*
Jenkins.instance.getAllItems(AbstractItem.class).each {
def job = jenkins.model.Jenkins.instance.getItem(it.fullName)
if (job!=null){
println "job: " + job;
int i = 1;
job.builds.each {
def build = it;
if (i<=10){
println "build: " + build.displayName + " will NOT BE DELETED";
}else{
println "build: " + build.displayName + " will BE DELETED";
it.delete();
}
i = ++i
}
}
};
The first loop will iterate over all Jenkins items and will store it under job var. If the job is not a Jenkins Job the result can be null, so the if (job!=null)
check is there to allow the code to proceed only for Jenkins jobs.
The int i = 1;
is the initialization of a counter for each job, that is incremented when a build is found. As far as I know, the build order is preserved, and the most recent build is returned first in the loop. When the counter reaches 10 or more, the if..else
enters the else
block and deletes the build it.delete()

Ioannis Barakos
- 1,319
- 1
- 11
- 16
-
I really appreciate your answer to my question, but what if I want to delete all jobs for a particular folder but not for jobs in another folder. – Antra Verma Oct 25 '19 at 16:36
-
The `it.fullName` will hold the folder name. You can use if/else statements before the `if (job!=null)` and decide what folders to delete or not – Ioannis Barakos Oct 27 '19 at 13:22