且构网

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

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

更新时间:2023-12-05 15:49:04

我找到了几种无需使用 REST API 或解析 XML 的方法:

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) }

这假设您没有删除或修改 Jenkins 中的默认全部"视图.当然,如果您确切地知道您的构建将在哪个视图中,您可以替换不同的视图名称.或者您可以尝试这种方法:

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 ...
      }
    }
  }
}

我认为可能有比 build.getResult().equals(null) 更准确的方法来确定构建是否正在运行,但我找不到好的方法API 文档,所以我不确定.这只是我发现使用对象自省的第一种方法.

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.

同样由于缺少 API 文档,我不确定我在这里使用的 Jenkins.instance.getItems()Jenkins.instance.getAllItems 之间是否存在显着差异() 用于 这个答案.

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.

最后,请注意,这些都是相对低效的方法.它们迭代每个作业的每个构建,因此如果您保存了很长的构建历史(默认设置是每个作业只保存 10 个构建的历史)或有数千个作业,这可能需要一段时间才能运行.见 我如何使用 Groovy 有效地列出当前在 Jenkins 上运行的 **All** 作业,以询问如何更有效地完成此任务.

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.