Groovy Script for Jenkins Script Console to Add or Modify Discard Old Builds Setting

When your Jenkins server runs on for a while, your hard disk usage grows up because the default setting of each job is that every job build and build artifact obtained from this are stored in a build history.  Limiting this build history can save hard disk usage. Each job has a setting option called Discard Old Builds. In this setting you can set how long (in days) old builds keep in the build history (criteria 1) or how many old builds keep at most in the build history (criteria 2). Jenkins matches first criteria 1 and then criteria 2. Beyond that there exists advanced setting options. This advanced setting options can configured how long and how many builds with build artifacts have to keep in the build history. After that Jenkins deletes the build artifact, but the logs, history, reports, etc for the build will be kept. These will be kept so as long as they match the criteria in the normal setting options. When you have many jobs, you don't want to configure every job manually. For that you can modify the Discard Old Builds setting in each job over a Groovy script at one go. Jenkins has a so-called Script Console [1].  In this console you have to put the following Groovy script and every job is modified to discard its old builds.

 1def daysToKeep = 28
 2def numToKeep = 10
 3def artifactDaysToKeep = -1
 4def artifactNumToKeep = -1
 5
 6Jenkins.instance.items.each { item ->
 7  println("=====================")
 8  println("JOB: " + item.name)
 9  println("Job type: " + item.getClass())
10
11  if(item.buildDiscarder == null) {
12    println("No BuildDiscarder")
13    println("Set BuildDiscarder to LogRotator")
14  } else {
15    println("BuildDiscarder: " + item.buildDiscarder.getClass())
16    println("Found setting: " + "days to keep=" + item.buildDiscarder.daysToKeepStr + "; num to keep=" + item.buildDiscarder.numToKeepStr + "; artifact day to keep=" + item.buildDiscarder.artifactDaysToKeepStr + "; artifact num to keep=" + item.buildDiscarder.artifactNumToKeepStr)
17    println("Set new setting")
18  }
19
20  item.buildDiscarder = new hudson.tasks.LogRotator(daysToKeep,numToKeep, artifactDaysToKeep, artifactNumToKeep)
21  item.save()
22  println("")
23
24}

This script is tested with Jenkins version 1.534 and Jenkins Subversion Plugin version 1.53. In my last posts ([2], [3]) I showed two other use cases for the Jenkins Script Console. All Groovy scripts can be found in GitHub [4]