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: trueto the map to stop siblings on the first failure.
Related guides
How to Read a YAML or JSON Config in a Jenkins PipelineParse a YAML or JSON file from the workspace in a Jenkins pipeline with readYaml and readJSON from the Pipeli…
How to Run a Stage on a Windows Agent in JenkinsTarget a Windows Jenkins agent for one stage with an agent label and run commands with the bat step instead o…