Skip to content

Instantly share code, notes, and snippets.

@tomnomnom
Created May 16, 2016 12:47
Show Gist options
  • Save tomnomnom/53998ec618a17d61153911f9b5ade0ed to your computer and use it in GitHub Desktop.
Save tomnomnom/53998ec618a17d61153911f9b5ade0ed to your computer and use it in GitHub Desktop.
Run a command once on each Jenkins slave using the CloudBees Workflow / Jenkins Pipeline plugin
// The ArrayList of slaves is not serializable, so fetching them should be marked as @NonCPS so that
// no attempt is made to serialize and save the local state of the function. See here for details:
// https://github.com/jenkinsci/pipeline-plugin/blob/master/TUTORIAL.md#serializing-local-variables
@NonCPS
def getSlaves() {
def slaves = []
hudson.model.Hudson.instance.slaves.each {
slaves << it.name
}
return slaves
}
// Run a command on each slave in series
getSlaves().each {
node(it) {
sh "hostname"
}
}
// Run a command on each slave in parallel
def jobs = [:]
getSlaves().each {
// Use a local variable to avoid closing over a reference to 'it',
// the value of which changes on each iteration
def slave = it
// Create a closure for each slave and put it in the map of jobs
jobs[slave] = {
node(slave) {
sh "hostname"
}
}
}
// Run the closures in parallel
parallel jobs
@stolenegg
Copy link

stolenegg commented Feb 2, 2017

I've found (at least with Jenkins 2, Workflow plugin 2.4, Groovy sandboxed) this second each iteration doesn't work. Using a for loop, however, does. e.g.

for (String slave : getSlaves()) {
    node(slave) {
        sh "hostname"   
    }
}

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