0
votes

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.

1
What is the 'script console'?Ioannis Barakos
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

1 Answers

1
votes

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()