Is there a way to get a list of RUNNING builds in Jenkins via a System Groovy Script? I tried looping through the busy executors, but from an executor object, I cannot get t
I found a couple ways to do this without using the REST API or parsing XML:
runningBuilds = Jenkins.instance.getView('All').getBuilds().findAll() { it.getResult().equals(null) }
This assumes that you have not deleted or modified the default "All" view in Jenkins. Of course you can substitute a different view name if you know exactly which view your builds are going to be in. Or you can try this approach:
runningBuilds = Jenkins.instance.getItems().collect { job->
job.builds.findAll { it.getResult().equals(null) }
}.flatten()
Although this approach doesn't require a view name, it also has limitations. It won't descend into folders or Multibranch Pipelines or anything like that. You'll need to manually descend into folders or concoct some way of doing it automatically. For instance, here's a version that works for a Multibranch Pipeline:
Jenkins.instance.getItemByFullName(multibranchPipelineProjectName).getItems().each { repository->
repository.getItems().each { branch->
branch.builds.each { build->
if (build.getResult().equals(null)) {
// do stuff here ...
}
}
}
}
I think there may be a more accurate method to use than build.getResult().equals(null)
to determine if a build is running or not, but I'm having trouble finding good API docs, so I'm not sure. This was just the first method that I found using object introspection that worked.
Again due to the lack of API docs, I'm not sure if there's a significant difference between Jenkins.instance.getItems()
which I used here and Jenkins.instance.getAllItems()
which was used in this answer.
Finally, note that these are all relatively inefficient methods. They iterate over every build of every job, so if you save a long history of builds (the default setting is to save a history of only 10 builds per job) or have thousands of jobs, this may take a while to run. See How do I Efficiently list **All** currently running jobs on Jenkins using Groovy for a question that asks how to do this task more efficiently.