Jenkins Pipeline: How to run stage(s) in all nodes that match label string ?
import jenkins.model.* | |
collectBuildEnv = [:] | |
@NonCPS | |
def getNodes(String label) { | |
jenkins.model.Jenkins.instance.nodes.collect { thisAgent -> | |
if (thisAgent.labelString.contains("${label}")) { | |
// this works too | |
// if (thisAagent.labelString == "${label}") { | |
return thisAgent.name | |
} | |
} | |
} | |
def dumpBuildEnv(String agentName) { | |
node("${agentName}") { | |
stage("Env in ${agentName}") { | |
echo "running on agent, ${agentName}" | |
sh 'printenv' | |
} | |
} | |
} | |
def processTask() { | |
// Replace label-string with the label name that you may have | |
def nodeList = getNodes("label-string") | |
for(i=0; i<nodeList.size(); i++) { | |
def agentName = nodeList[i] | |
// skip the null entries in the nodeList | |
if (agentName != null) { | |
println "Prearing task for " + agentName | |
collectBuildEnv["node_" + agentName] = { | |
dumpBuildEnv(agentName) | |
} | |
} | |
} | |
} | |
pipeline { | |
// I prefer to have a dedicated node to execute admin tasks | |
agent { | |
label "admin-agent" | |
} | |
options { | |
timestamps() | |
} | |
stages { | |
stage('agents-tasks') { | |
steps { | |
script { | |
processTask() | |
parallel collectBuildEnv | |
} | |
} | |
} | |
} | |
} |
This comment has been minimized.
This comment has been minimized.
#NOTE# Value for "label-string" (handled in line 27) is |
This comment has been minimized.
This comment has been minimized.
Worked for me. |
This comment has been minimized.
This comment has been minimized.
@aviadcye |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This comment has been minimized.
Tested on Jenkins instance running v2.32.2, had to whitelist couple of methods, though.