Jenkins delete builds older than latest 20 builds for all jobs

十年热恋 提交于 2019-12-05 08:17:20
Dave Bacher

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.

There are lots of ways to do this

Personally I would use the 'discard old builds' in the job config

If you have lots of jobs you could use the CLI to step through all the jobs to add it

Alternatively there is the configuration slicing plugin which will also do this for you on a large scale

For Multibranch Pipelines, I modified the script by Dave Bacher a bit. Use this to delete builds older than the latest 20 build of "master" branches:

MAX_BUILDS = 20

for (job in Jenkins.instance.items) {
  if(job instanceof jenkins.branch.MultiBranchProject) {
    job = job.getJob("master")
    def recent = job.builds.limit(MAX_BUILDS)
    for (build in job.builds) {
      if (!recent.contains(build)) {
        println "Preparing to delete: " + build
        // build.delete()
      }
    }
  }
}
chanukhya bachina

This can be done in many ways. You can try the following

  1. get all your job names in a textfile by going to the jobs location in jenkins and run the following

ls >jobs.txt

Now you can write a shell script with a for loop

#!/bin/bash
##read the jobs.txt
for i in 'cat <pathtojobs.txt>'
     do
curl -X POST http://jenkins-host.tld:8080/jenkins/job/$i/[1-9]*/doDeleteAll
     done

the above deletes all the jobs

you can also refer here for more answers

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()
    }
  }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!