Search code examples
jenkinsgroovyjenkins-pipeline

In Jenkins, how can I disable a job's "Discard old builds" via pipeline code?


I have a lot of Jenkins jobs that has this option enabled in their configuration page Discard old builds enabled

How can I disable it via pipeline code so it'll be this?

enter image description here

Here's the prototype

import hudson.model.*

Hudson.instance.getAllItems(Job.class).each {
    if (it.fullName.contains("someJobName")) {
        // Disable "Discard old builds"
        it.discardOldBuilds(disabled) // pseudo code
    }
}

Solution

  • You can use the Jenkins management Script Console to run a system groovy script that will modify the BuildDiscarder for all jobs. You can use something like:

    def numToKeep = 7
    def daysToKeep = 7
    def artifactDaysToKeep = -1   // -1 is an empty value
    def artifactNumToKeep = -1    // -1 is an empty value
    
    
    Jenkins.instance.getAllItems(Job.class).each { item ->
      println("******************")
      println("Job Name: ${item.fullName}")
      println("Job type: ${item.getClass()}\n")
    
      println("Current BuildDiscarder configuration:")
      if(item.buildDiscarder) {
         println("BuildDiscarder: ${item.buildDiscarder.getClass()}")
         println("Current 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}\n")
      }
      else {
         println("No BuildDiscarder is configured\n")
      }
    
      println("Setting new LogRotator settings")
      item.buildDiscarder = new hudson.tasks.LogRotator(daysToKeep,numToKeep, artifactDaysToKeep, artifactNumToKeep)
      item.save()  // save the job with the new config
      println("Job configured")
    }
    

    This is the basic script for configuring the LogRotator across all jobs.
    If you want to disable the configuration you have two options:

    1. Disable the configuration entirely - (alike your screenshot) In this case you must disable the existing configuration by assigning null to that jobs value.
    ...
     item.buildDiscarder = null // reset the buildDiscarder configuration
     item.save()               // save the job with the new config
    ...
    
    1. Set all values to -1 - this will leave the LogRotator configuration but with empty values - so it actually doesn't do anything but is still there for future modifications
    def numToKeep = -1
    def daysToKeep = -1
    def artifactDaysToKeep = -1
    def artifactNumToKeep = -1 
    ...
    item.buildDiscarder = new hudson.tasks.LogRotator(daysToKeep,numToKeep, artifactDaysToKeep, artifactNumToKeep)
    item.save() 
    ...
    

    enter image description here