如何获取分配了标签的所有Jenkins节点的列表,包括主节点?

Pat*_* B. 11 jenkins jenkins-groovy jenkins-pipeline

我正在创建一个Jenkins管道作业,我需要在标有某个标签的所有节点上运行作业.

因此,我正在尝试获取分配了特定标签的节点名称列表.(使用节点我可以获得标签getAssignedLabels())

nodes-list中jenkins.model.Jenkins.instance.nodes似乎不包含主节点,我需要在我的搜索中包含.

我目前的解决方案是迭代jenkins.model.Jenkins.instance.computers并使用getNode()-method来获取节点.这是有效的,但在詹金斯的javadoc我正在阅读这个列表可能不是最新的.

从长远来看,我将添加(动态)云节点,我担心我将无法使用computers.

什么是正确获取所有当前节点的列表?

这就是我现在正在做的事情:

@NonCPS
def nodeNames(label) {
    def nodes = []
    jenkins.model.Jenkins.instance.computers.each { c ->
        if (c.node.labelString.contains(label)) {
            nodes.add(c.node.selfLabel.name)
        }
    }   
    return nodes
}
Run Code Online (Sandbox Code Playgroud)

tow*_*wel 12

更新的答案:在管道中用于nodesByLabel获取分配给标签的所有节点。

  • 这是更现代的答案。你甚至可以这样做:`nodeList =nodesByLabel label: 'LABEL1||LABEL2&&!ANOTHER',offline: true` (4认同)
  • 要使用它,您需要安装“Pipeline Utility Steps”。请参阅 https://plugins.jenkins.io/pipeline-utility-steps/ (2认同)

Bor*_*ris 9

这是一个更具可读性和简洁性的功能解决方案:

def nodes = jenkins.model.Jenkins.get().computers
  .findAll{ it.node.labelString.contains(label) }
  .collect{ it.node.selfLabel.name }
Run Code Online (Sandbox Code Playgroud)

您可以在 Jenkins脚本控制台中验证它。


Pat*_* B. 8

这就是我现在正在做的方式。我还没有发现其他东西:

@NonCPS
def hostNames(label) {
  def nodes = []
  jenkins.model.Jenkins.instance.computers.each { c ->
    if (c.node.labelString.contains(label)) {
      nodes.add(c.node.selfLabel.name)
    }
  }
  return nodes
}
Run Code Online (Sandbox Code Playgroud)

jenkins.model.Jenkins.instance.computers 包含主节点和所有从节点。

  • 您的代码会导致“groovy.lang.MissingPropertyException: No such property: get for class: jenkins.model.Jenkins”。请将`jenkins.model.Jenkins.get`更改为`jenkins.model.Jenkins.get()` (2认同)

小智 6

更新@patrick-b 答案:如果您的标签包含相同的字符串,则包含可能有问题,我添加了一个拆分步骤,请检查每个用空格分隔的标签。

@NonCPS
def hostNames(label) {
    def nodes = []
    jenkins.model.Jenkins.get.computers.each { c ->
        c.node.labelString.split(/\s+/).each { l ->
            if (l != null && l.equals(label)) {
                nodes.add(c.node.selfLabel.name)
             }
        }
    }

    return nodes
}
Run Code Online (Sandbox Code Playgroud)