Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jenkins delete builds older than latest 20 builds for all jobs

I am in the process of cleaning up Jenkins (it was setup incorrectly) and I need to delete builds that are older than the latest 20 builds for every job.

Is there any way to automate this using a script or something?

I found many solutions to delete certain builds for specific jobs, but I can't seem to find anything for all jobs at once.

Any help is much appreciated.

like image 459
Fadi Avatar asked Feb 24 '16 18:02

Fadi


People also ask

How do I remove old builds in Jenkins?

Delete a Jenkins build via GUI. Go into the build you want to delete, and click the Delete this build button in the upper right corner. If you need to clean the Jenkins build history, and reset the build number back to 1, you can run a simple script in Jenkins Script Console.

How do you change the number of builds kept by Jenkins?

This is a feature that is given to you by Jenkins so you can change the number of builds you want to keep. If you are using a Declarative pipeline you can just add this to your code: pipeline { options { buildDiscarder(logRotator(numToKeepStr: '30', artifactNumToKeepStr: '30')) } ... }

How do I get rid of Jenkins keep this build forever?

You can remove a build by deleting the named directory on the master under $HUDSON_HOME/jobs/job-name/builds/42 (though that's from memory, so might not be exact). If you just want to remove the artifacts, remove the archive subdirectory.


2 Answers

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.Jenkins
import hudson.model.Job

MAX_BUILDS = 20

for (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.

like image 81
Dave Bacher Avatar answered Sep 20 '22 11:09

Dave Bacher


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.Jenkins
import hudson.model.Job

MAX_BUILDS = 5
Jenkins.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()
    }
  }
}
like image 42
Johnny Doe Avatar answered Sep 22 '22 11:09

Johnny Doe