Skip to content
Latchkey

How to Build Dynamic Parallel Branches in Jenkins

The parallel step accepts a map of name to closure, so you can build branches from a list at runtime.

Construct a Map<String, Closure> (often with collectEntries) and pass it to parallel. This runs one branch per entry, which is how you fan out over a dynamic list of targets.

Steps

  • Build a map of branch name to a closure of steps.
  • Capture the loop variable into a local so each closure binds correctly.
  • Pass the map to parallel.

Jenkinsfile

Jenkinsfile
pipeline {
  agent any
  stages {
    stage('Fan out') {
      steps {
        script {
          def targets = ['us-east', 'us-west', 'eu-central']
          def branches = targets.collectEntries { t ->
            [(t): { sh "./deploy.sh --region ${t}" }]
          }
          parallel branches
        }
      }
    }
  }
}

Gotchas

  • Bind the loop variable to a local inside the closure or every branch sees the last value.
  • Add failFast: true to the map to stop siblings on the first failure.

Related guides

Run this faster and cheaper on Latchkey managed runners. Start free →