Interview Prep/Jenkins/Scripted pipeline, Groovy & CPS

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.

All Jenkins questions Roadmap: Jenkins

More on Scripted pipeline, Groovy & CPS