Jenkins delete builds older than latest 20 builds for all jobs

前端 未结 6 568
悲哀的现实
悲哀的现实 2021-01-02 01:30

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 an

6条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-02 02:17

    I had issues running the suggestions on my Jenkins instance. It could be because it is dockerized. In any case, removing the folder beforehand using the underlying bash interpreter fixes the issue. I also modified the script to keep 180 days of build logs and keep a minimum of 7 build logs:

    import jenkins.model.Jenkins
    import hudson.model.Job
    
    MIN_BUILD_LOGS = 7
    
    def sixMonthsAgo = new Date() - 180
    
    Jenkins.instance.getAllItems(Job.class).each { job ->
      println job.getFullDisplayName()
      
      def recent = job.builds.limit(MIN_BUILD_LOGS)
      
      def buildsToDelete = job.builds.findAll {
        !recent.contains(it) && ! (it.getTime() > sixMonthsAgo)
      }
      
      if (!buildsToDelete) {
        println "nothing to do"
      }
      for (build in buildsToDelete) {
        println "Preparing to delete: " + build + build.getTime()
        ["bash", "-c", "rm -r " + build.getRootDir()].execute()
        build.delete()
      }
    }
    
    "done"
    

提交回复
热议问题