How do you generate parallel stages dynamically?
AdvancedConceptScripted pipeline, Groovy & CPS
Answer
Build a map of branch names to closures and pass it to the parallel step inside script {}.
script {
def services = sh(script: 'ls services', returnStdout: true).trim().split('\n')
def branches = [:]
for (s in services) {
def svc = s // capture per iteration
branches[svc] = { stage(svc) { sh "make -C services/${svc} test" } }
}
branches.failFast = true
parallel branches
}
The def svc = s copy matters: otherwise every closure captures the same loop variable.
More on Scripted pipeline, Groovy & CPS
What does a scripted pipeline look like and when would you still write one?IntermediateWhat is CPS and why does Jenkins transform pipeline Groovy?AdvancedWhy does `java.io.NotSerializableException` happen in pipelines?AdvancedWhat does `@NonCPS` do and what are its rules?AdvancedWhy do some Groovy closures behave unexpectedly in pipelines, for example `list.each { }` or `sort`?AdvancedWhat is the `script` block in declarative, and what are its limits?Beginner