How to Use Retry in Jenkins Pipeline for Reliable Builds
In Jenkins Pipeline, use the
retry step to automatically rerun a block of code a specified number of times if it fails. Wrap the steps you want to retry inside retry(count) { ... }, where count is the number of attempts.Syntax
The retry step syntax is simple. You specify how many times Jenkins should retry the enclosed block if it fails.
retry(count) { ... }: Runs the code inside the braces up tocounttimes until it succeeds.- If the code succeeds before reaching the max retries, it continues without retrying further.
- If all retries fail, the pipeline fails.
groovy
retry(3) { // steps to retry }
Example
This example shows a Jenkins Declarative Pipeline that retries a shell command up to 3 times if it fails.
groovy
pipeline {
agent any
stages {
stage('Retry Example') {
steps {
retry(3) {
sh 'exit 1' // This command fails intentionally
}
}
}
}
}Output
[Pipeline] retry
[Pipeline] {
[Pipeline] sh
+ exit 1
[Pipeline] // sh
[Pipeline] sh
+ exit 1
[Pipeline] // sh
[Pipeline] sh
+ exit 1
[Pipeline] // sh
[Pipeline] }
[Pipeline] // retry
[Pipeline] }
[Pipeline] // stage
[Pipeline] End of Pipeline
ERROR: script returned exit code 1
Finished: FAILURE
Common Pitfalls
Common mistakes when using retry include:
- Retrying too many times can waste build time.
- Not wrapping only the flaky steps, causing unnecessary retries of stable steps.
- Using
retrywithout proper error handling can hide real issues. - For Declarative Pipelines,
retrymust be insidestepsblock.
groovy
/* Wrong: retry outside steps block in Declarative Pipeline */ pipeline { agent any stages { stage('Bad Retry') { retry(3) { sh 'exit 1' } } } } /* Right: retry inside steps block */ pipeline { agent any stages { stage('Good Retry') { steps { retry(3) { sh 'exit 1' } } } } }
Quick Reference
- retry(count) { ... }: Retry enclosed steps up to
counttimes. - Use for flaky commands or network calls.
- Place inside
stepsblock in Declarative Pipelines. - Fail pipeline if all retries fail.
Key Takeaways
Use
retry(count) { ... } to rerun failing steps automatically in Jenkins Pipeline.Place
retry inside the steps block in Declarative Pipelines.Limit retries to avoid wasting build time on persistent failures.
Wrap only flaky or unstable steps to keep pipelines efficient.
If all retries fail, the pipeline will fail, signaling a real problem.