Last active
February 24, 2025 10:54
-
-
Save mramanathan/b1e7e92a3953d28b3b9f856f6bb18412 to your computer and use it in GitHub Desktop.
Jenkins Pipeline: How to run stage(s) in all nodes that match label string ?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} | |
} | |
} | |
} | |
} |
#NOTE#
Value for "label-string" (handled in line 27) is case sensitive
.
Worked for me.
Thanks :)
@aviadcye
Nice to hear that. Thanks for the feedback.
👍
Worked as expected, nice!
Little typo in L10. thisAagent
-> thisAgent
You don't need to use any restricted functions if you use the nodesByLabel step in a scripted pipeline
def nodeList = nodesByLabel label: MyLabel, offline: false
Set offline: true if you want to also select agents that are offline.
stage('Checkout') {
agent { label "jenkinsnodes" }
steps {
script {
def nodes = nodesByLabel label: 'jenkinsnodes'
nodes = nodes.sort()
Map tasks = [:]
for (int i = 0; i < nodes.size(); i++) {
def label = nodes[i]
def stageName = "Checkout ${nodes[i]}"
tasks[label] = {
node(label) {
stage(stageName) {
checkout scm
}
}
}
}
timeout(time: 3, unit: 'MINUTES') {
parallel(tasks)
}
}
}
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Tested on Jenkins instance running v2.32.2, had to whitelist couple of methods, though.