Jenkins : Add a new label to agents meeting a condition

This script shows how to alter the slave nodes' label membership. In this case we create a new label if the existing label contains a string. It has been tested from the Jenkins command window.

import jenkins.model.*
//Groovy script to add a label to all slave nodes having labels matching a certain specification.

for (slave in jenkins.model.Jenkins.instance.slaves) {
    oldLabelName = slave.getLabelString()

    if (oldLabelName.contains('WIN2012')) {

        newLabelName = oldLabelName + " " + "WIN2012.X"
        slave.setLabelString(newLabelName)
    }
}