How to get a list of all Jenkins nodes assigned with label including master node?

后端 未结 6 1325
囚心锁ツ
囚心锁ツ 2021-02-18 21:25

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

相关标签:
6条回答
  • 2021-02-18 21:59

    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
    }
    
    0 讨论(0)
  • 2021-02-18 22:04

    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.

    0 讨论(0)
  • 2021-02-18 22:07

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

    0 讨论(0)
  • 2021-02-18 22:12

    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.

    0 讨论(0)
  • 2021-02-18 22:22

    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.

    0 讨论(0)
  • 2021-02-18 22:22

    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.

    0 讨论(0)
提交回复
热议问题