Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Jenkins Groovy script to find unused jobs. Unused means 'not built for more than X days'
import jenkins.model.Jenkins
import jenkins.model.JenkinsLocationConfiguration
String jobNameRegexp = ".*"
long maxThresholdDays = 60; // days
boolean ignoreDisabledJobs = true
def getLastBuildTime(Job job) {
def lastBuild = job.getLastBuild()
if(lastBuild == null) {
return new Date(0)
} else {
return lastBuild.getTime()
}
}
Date currentDate = new Date()
def oldJobs = Jenkins.instance.items
.findAll { job -> job.name =~ jobNameRegexp }
.findAll { job ->
def item = Jenkins.instance.getItem(job.name)
def lastBuildTime = getLastBuildTime(item)
boolean tooOld = lastBuildTime.before(new Date((currentDate.getTime() - (maxThresholdDays * 24L * 60 * 60 * 1000))))
if (ignoreDisabledJobs) {
return tooOld && job.buildable
} else {
return tooOld
}
}
.sort { getLastBuildTime(it) }
jlc = new JenkinsLocationConfiguration()
oldJobs.each {
println "${it.name} - ${getLastBuildTime(it)}, disabled = ${!it.buildable}"
}
return
@daniilyar-incountry

This comment has been minimized.

Copy link

@daniilyar-incountry daniilyar-incountry commented Apr 22, 2020

If you use Jenkins folders then this one will work for you:

import jenkins.model.Jenkins
import jenkins.model.JenkinsLocationConfiguration

String jobNameRegexp = ".*"
long maxThresholdDays = 60; // days

def getLastBuildTime(Job job) {
  def lastBuild = job.getLastBuild()
  if(lastBuild == null) {
    return new Date(0)
  } else {
    return lastBuild.getTime()
  }
}

Date currentDate = new Date()
def folders = Jenkins.instance.items.findAll { job -> job.name =~ jobNameRegexp }

def oldJobs = []

folders.each {
  for (job in it.getAllJobs()) {
    if(job != null) { // && job.buildable
      def item = Jenkins.instance.getItemByFullName(job.getFullName())
      def lastBuildTime = getLastBuildTime(item)
      if(lastBuildTime.before(new Date((currentDate.getTime() - (maxThresholdDays * 24L * 60 * 60 * 1000))))){
        oldJobs.add(job)
      }
    }
  }
}

oldJobs.sort { getLastBuildTime(it) }

jlc = new JenkinsLocationConfiguration()
oldJobs.each {
  println "'${it.getFullName()}' - ${getLastBuildTime(it)}, disabled = ${!it.buildable}"
}

return

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.