Search code examples
jenkinsjenkins-pipelinejenkins-groovyjenkins-cli

Is there a way to bulk delete unused jenkins jobs? (not run in the last 6 months)


I have a Jenkins instance with multiple teams using it. It gets cluttered frequently and people don't delete their test jobs after testing. Is there a way to delete unused jobs (not run in the last 6 months) including their workspace?


Solution

  • You can use the following Groovy script for this. Comment out the delete part and test it before using just to make sure it's what you need :)

    def deleteBefore = "2022/07/01"
    
    Jenkins.instance.getAllItems(Job.class).each { jobitem ->
      def jobName = jobitem.getFullName()
    
      def deleteBeforeTime = new Date(deleteBefore).getTime()
    
      def build = jobitem.getLastBuild() 
    
      if(build == null || build.getTimeInMillis() <= deleteBeforeTime){ // If no builds, build is null
    
        println build == null ? "Job " + jobName + " has never run, deleting the Job" : "Job " + jobName + " last ran on (" + build.getTime() + ") hence deleting"
        jobitem.delete()
      }    
    }