How to get a list of all Jenkins nodes assigned wi

2020-07-02 02:30发布

问题:

I'm creating a Jenkins pipeline job and I need to run a job on all nodes labelled with a certain label.

Therefore I'm trying to get a list of node names assigned with a certain label. (With a node I can get the labels with getAssignedLabels())

The nodes-list in jenkins.model.Jenkins.instance.nodes seems not contain the master-node which I need to include in my search.

My current solution is to iterate over the jenkins.model.Jenkins.instance.computers and use the getNode()-method to get the node. This works, but in the javadoc of Jenkins I'm reading the this list might not be up-to-date.

In the long-run I will add (dynamically) cloud-nodes and I'm afraid that I won't be able to use computers then.

What is the right get the list of all current nodes?

This is what I'm doing right now:

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

回答1:

This is the way I'm doing right now. I haven't found something else:

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

jenkins.model.Jenkins.get.computers contains the master-node and all the slaves.



回答2:

Updated answer: in a pipeline use nodesByLabel to get all nodes assigned to a label.



回答3:

Update to @patrick-b answer : contains can be buggy if you have labels containing same string, I've added a split step do check every label separated with spaces.

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


回答4:

I think that you can do this with:

def nodes = Jenkins.get.getLabel('my-label').getNodes()
for (int i = 0; i < nodes.size(); i++) {
    node(nodes[i].getNodeName()) {
        // on node
    }
}

I don't know for sure whether this works with cloud nodes.



回答5:

Try using for (aSlave in hudson.model.Hudson.instance.slaves) {} and aSlave.getLabelString()); to get all the labels for all of your nodes. You can construct a list of nodes per label this way.