How to Use Parallel Stages in Jenkins Pipeline
In Jenkins Pipeline, you use the
parallel step inside a stage to run multiple stages at the same time. Define each parallel branch as a separate block inside parallel, and Jenkins will execute them concurrently.Syntax
The parallel step runs multiple branches simultaneously inside a stage. Each branch is a named block with its own steps.
- stage: Defines a pipeline stage.
- parallel: Runs multiple branches at the same time.
- branch name: Label for each parallel task.
- steps: Commands or actions to run in each branch.
groovy
stage('Parallel Stage') { parallel( branch1: { // steps for branch1 }, branch2: { // steps for branch2 } ) }
Example
This example shows a Jenkins Declarative Pipeline with a stage that runs two tasks in parallel: one prints a message and the other waits 3 seconds before printing.
groovy
pipeline {
agent any
stages {
stage('Parallel Stage') {
parallel {
branch1 {
echo 'Running branch 1'
}
branch2 {
sleep 3
echo 'Running branch 2 after 3 seconds'
}
}
}
}
}Output
[Pipeline] stage
[Pipeline] { (Parallel Stage)
[Pipeline] parallel
[Pipeline] { (branch1)
[Pipeline] echo
Running branch 1
[Pipeline] }
[Pipeline] { (branch2)
[Pipeline] sleep
Sleeping for 3 sec
[Pipeline] echo
Running branch 2 after 3 seconds
[Pipeline] }
[Pipeline] }
[Pipeline] }
[Pipeline] // stage
Common Pitfalls
Common mistakes when using parallel stages include:
- Not wrapping parallel branches inside a
stage, causing syntax errors. - Using the wrong syntax for parallel branches (e.g., missing branch names).
- Trying to use
paralleloutside of astageblock. - Not handling shared resources properly, which can cause conflicts when branches run simultaneously.
groovy
/* Wrong: parallel used outside stage */ parallel( branch1: { echo 'Task 1' }, branch2: { echo 'Task 2' } ) /* Right: parallel inside a stage */ stage('Parallel Stage') { parallel( branch1: { echo 'Task 1' }, branch2: { echo 'Task 2' } ) }
Quick Reference
Tips for using parallel stages in Jenkins Pipeline:
- Always define
parallelinside astage. - Name each parallel branch clearly for easy identification.
- Use
echo,sh, or other steps inside branches. - Be mindful of shared workspace or resources to avoid conflicts.
- Use parallel stages to speed up builds by running independent tasks simultaneously.
Key Takeaways
Use the
parallel step inside a stage to run multiple branches concurrently.Each parallel branch must have a unique name and its own steps.
Parallel stages speed up pipelines by running tasks at the same time.
Always place
parallel inside a stage block to avoid syntax errors.Be careful with shared resources when running parallel branches to prevent conflicts.