将所有构建限制到给定节点的 Jenkins 脚本

Jenkins Script to Restrict all builds to a given node

我们最近为我们的 Jenkins 构建环境添加了第二个从节点 运行 一个不同的 OS(Linux 而不是 Windows)用于特定构建。毫不奇怪,这意味着我们需要通过 "Restrict where this project can be run" 设置来限制构建。然而,我们有很多构建 (100+),所以点击它们来手动更改此设置的前景并不让我兴奋。

有人可以提供 groovy 脚本来通过 Jenkins 脚本控制台实现此目的吗?我过去曾使用过类似的脚本来更改其他设置,但找不到有关此特定设置的任何参考。

你可以试试Jenkins Job-DSL plugin

这将允许您创建一个工作来改变您的其他工作。这通过在基于 groovy 的 DSL 中提供构建步骤来修改其他作业来实现。

这里的这个将为作业添加标签 'xxxx'。我通过使用作业本身作为模板来作弊。

job{
  using 'xxxx'
  name 'xxxx'
  label 'Linux'
}

如果你们中的一些工作类型不同,您可能需要调整它

设法根据以前的脚本和 Jenkins 源代码为自己找出脚本。脚本如下:

import hudson.model.*
import hudson.model.labels.*
import hudson.maven.*
import hudson.tasks.*
import hudson.plugins.git.*

hudsonInstance = hudson.model.Hudson.instance
allItems = hudsonInstance.allItems
buildableItems = allItems.findAll{ job -> job instanceof BuildableItemWithBuildWrappers }

buildableItems.each { item ->
  boolean shouldSave = false
  item.allJobs.each { job ->
    job.assignedLabel = new LabelAtom('windows-x86') 
  }
}

将 'windows-x86' 替换为您需要的节点标签。如有必要,您还可以根据 item.name 进行条件更改以过滤掉一些工作。