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
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
}
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.
Updated answer: in a pipeline use nodesByLabel to get all nodes assigned to a label.
Here is a functional solution which is more readable and concise:
def nodes = jenkins.model.Jenkins.get().computers
.findAll{ it.node.labelString.contains(label) }
.collect{ it.node.selfLabel.name }
You can verify it in the Jenkins Script Console.
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.
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.