Find Jobs In All Jenkins Folders
Sometimes it is useful to list or apply an operation to a Jenkins job based on a regular expression. The Jenkins DSL plugin, which executes Groovy code within Jenkins, is probably the easier way to achieve this.
I was able to find code snippets in my first web search. However, all the solutions I found had a major limitation: not dealing with Jenkins folder.
In case you have not used them yet, Jenkins folders is a great plugin that let you organise your jobs into "container" folders, just like you would do on a file system.
Searching recursively
The following Groovy snippet will return a list of jobs across all folders. Optionally, you can pass a regular expression to filter out jobs by name. This regulare expression will be matched against the full name of the job, that is, including folder names. This allows you, for example, to find all unit tests jobs in a folder.
def isFolder(abstractJob){
return abstractJob.getClass().getName() == "com.cloudbees.hudson.plugins.folder.Folder"
}
def collectJobRecursively(abstractJob,resultCollector){
if(isFolder(abstractJob))
{
abstractJob.items.findAll().each{ nestedJob ->
collectJobRecursively(nestedJob,resultCollector)
}
}
else
{
//only add actual jobs to the list
resultCollector << abstractJob
}
}
def findAll(pattern = '.*'){
def resultCollector = []
Jenkins.instance.items.findAll().each{ job ->
collectJobRecursively(job,resultCollector)
}
return resultCollector
.findAll{
// apply the regular expression here.
// we are matching the Full Name (including folder names)
(it.fullName =~ /$pattern/)
}
}
Using the recursive findAll function
You can now use the previous findAll
function to search for all unit test jobs in a folder called "master_branch":
findAll(".*/master_branch/.*UnitTest.*")
.each{
job ->
if(job.lastBuild){
println job.fullName + ':' + job.lastBuild.result
}
else {
println job.fullName + " has not run yet";
}
}