且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何通过groovy脚本获取正在运行的jenkins构建列表?

更新时间:2023-12-05 13:56:34

I found a way to do this without using the REST API or parsing XML:

Jenkins.instance.getItems().each { job->
  job.builds.each { build->
    if (build.getResult().equals(null)) {
      // do stuff here...
    }
  }
}

Note that this 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 this is a relatively inefficient method. It iterates 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.