Skip to content

Instantly share code, notes, and snippets.

@j-rivero
Last active December 13, 2022 00:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save j-rivero/9b7b04215fc9ee1a434873ce63a4ffea to your computer and use it in GitHub Desktop.
Save j-rivero/9b7b04215fc9ee1a434873ce63a4ffea to your computer and use it in GitHub Desktop.

Jenkins Groovy snippets

Jobs

  • Remove jobs
import jenkins.model.*

def matchedJobs = Jenkins.instance.items.findAll { job ->
    job.name =~ /my_regex_here/
}
    
matchedJobs.each { job ->
    println job.name
    //job.delete()
}
  • Remove queue jobs
import hudson.model.*
import jenkins.model.Jenkins

def q = Jenkins.instance.queue

q.items.findAll { it.task.name.startsWith('regexp_here') }.each { q.cancel(it.task) }
  • Remove old jobs
// Set how old the jobs to list should be (in days)
def numDaysBack = 700


def cutOfDate = System.currentTimeMillis() - 1000L * 60 * 60 * 24 * numDaysBack

for (job in Jenkins.instance.getAllItems(Job.class)) {
  build = job.getLastSuccessfulBuild()
  if (build != null && build.getTimeInMillis() < cutOfDate) {
    println job.getFullName()
  }
}
  • Cleanup workspaces
import jenkins.model.*

def matchedJobs = Jenkins.instance.items.findAll { job ->
    job.name =~ /ignition_msgs.*windows/
}
    
matchedJobs.each { job ->
    println job.name
    if (job.building) {
      println "Skipping job $job.name, currently building"
    } else {
      println "Wiping out workspace of $job.name"
      job.doDoWipeOutWorkspace()
  }
}
  • Rename jobs
import jenkins.model.*

def matchedJobs = Jenkins.instance.items.findAll { job ->
    job.name =~ /-gazebo11.*bionic.*/
}
    
matchedJobs.each { job ->
    new_name = job.name.replace('bionic','focal')
    if (jenkins.model.Jenkins.instance.getItem(new_name) != null) {
  	   println " = Job " + new_name + " exists!"
    } else {
    	println " * " + job.name + " ----> " + new_name
      // job.renameTo(new_name)
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment