Wednesday, May 17, 2017

Jenkins groovy script to find the node on which the last build built for a job

The below code is intended to be run in Jenkins script console

Problem

I want to find the jenkins node on which the last build of the job "my-job-name" built. This script determined that, it ran on centos5-x64-01

Code

def getJobs() {
 def hi = hudson.model.Hudson.instance
 return hi.getItems(hudson.model.Job)
}

def getBuildJob(String jobNam) {
 def buildJob = null
 def jobs = getJobs()
 (jobs).each { job ->
 if (job.displayName == jobNam) {
 println("Found")
 println("Exiting job search")
 buildJob = job
 return buildJob
 }
 }
 return buildJob
}

job_name = "my-job-name"

job_id = getBuildJob(job_name)

last_build = job_id.getBuilds()[0]

println("Recent Builds of the job " + job_name + " " + job_id.getBuilds())
println("last_build="+last_build)

println("The last_build of Job " + job_name + " builton the node " +last_build.getBuiltOn())


Output

Found
Exiting job search
Recent Builds of the job my-job-name [my-job-name #1474, my-job-name #1473, my-job-name #1472, my-job-name #1466, my-job-name #1421]
last_build=my-job-name #1474
The last_build of Job my-job-name builton the node hudson.slaves.DumbSlave[centos5-x64-01]

Reference