Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get node names from labels in a Jenkins pipeline script

I have a set of virtual machines for testing my build results. All VMs are configured as Jenkins slave nodes. The master node can start and stop the VMs.

The VMs are tagged in groups of three (cluster1, cluster2), and with different roles (role1, role2, role3).

I'd like to write a pipeline script that takes a GROUP name as its argument (StringParameterValue) and

  1. start the VMs that belong to the group
  2. run individual tests on each node (in parallel)
  3. stop the VMs after completion.

The pipeline script looks roughly like:

def VM1 = ??? get name of the node labeled ("GROUP && role1") ???;
def VM2 = ??? get name of the node labeled ("GROUP && role2") ???;
def VM3 = ??? get name of the node labeled ("GROUP && role3") ???;
def VMs = [VM1, VM2, VM3];

node (master) {

    stage 'Start'
    def start = [:];
    for ( vm in VMs ) {
        start["${vm}"] = {
            build job: 'Start_VM', parameters: [
                [$class: 'StringParameterValue', name: 'VMNAME', value: vm]];
        }
    }
    parallel start;

    def tests = [:];
    for (int i = 0; i < VMs.size; i++) {
        tests["role${i}"] = {
            node (VMs[i]) {
                build job: "Test_role${i}";
            }
        }
    }
    parallel tests;

    Stage 'Stop'
    def stop = [:];
    for ( vm in VMs ) {
        stop["${vm}"] = {
            build job: 'Stop_VM', parameters: [
                [$class: 'StringParameterValue', name: 'VMNAME', value: vm]];
        }
    }
    parallel stop;
}

Q: How can I derive the individual node names by the group label?

like image 510
chris_f Avatar asked Aug 04 '16 18:08

chris_f


1 Answers

I implemented a function that fetches the node names from their labels:

def roles = ['role1', 'role2', 'role3'];

def getNodeNames (group, roles) {
    def lgroup = Jenkins.instance.getLabel(group)
    def result = [:]

    for (role in roles) {
        def lrole = lgroup.and(Jenkins.instance.getLabel(role))
        def nodes = lrole.getNodes()
        if (nodes.size() > 0) {
            result[role] = nodes[0].getNodeName()
        }
    }
    print "getNodeNames($group) = ${result}"
    return result
}

def VMs = getNodeNames(GROUP)
like image 73
chris_f Avatar answered Nov 15 '22 04:11

chris_f