Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
}
}
}
}
}
@mramanathan

This comment has been minimized.

Copy link
Owner Author

@mramanathan mramanathan commented Nov 20, 2018

Tested on Jenkins instance running v2.32.2, had to whitelist couple of methods, though.

@mramanathan

This comment has been minimized.

Copy link
Owner Author

@mramanathan mramanathan commented Dec 7, 2018

#NOTE#

Value for "label-string" (handled in line 27) is case sensitive.

@aviadcye

This comment has been minimized.

Copy link

@aviadcye aviadcye commented Dec 7, 2020

Worked for me.
Thanks :)

@mramanathan

This comment has been minimized.

Copy link
Owner Author

@mramanathan mramanathan commented Dec 10, 2020

@aviadcye
Nice to hear that. Thanks for the feedback.

👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment