How to Use Post Failure in Jenkins Pipeline
In Jenkins Pipeline, use the
post section with a failure block to run steps only when the build fails. This helps you automate tasks like notifications or cleanup after a failure.Syntax
The post section in a Jenkins Pipeline defines actions that run after the main pipeline stages. Inside post, the failure block runs only if the build fails.
post: Defines post-build actions.failure: Runs steps when the build fails.- Inside
failure, you add the steps to execute on failure.
groovy
pipeline {
agent any
stages {
stage('Example') {
steps {
// Your build steps here
}
}
}
post {
failure {
// Steps to run if build fails
}
}
}Example
This example shows a pipeline that deliberately fails and uses the post failure block to print a message and send a notification.
groovy
pipeline {
agent any
stages {
stage('Failing Stage') {
steps {
echo 'This stage will fail'
script {
error('Failing the build intentionally')
}
}
}
}
post {
failure {
echo 'Build failed! Sending notification...'
// Here you could add email or Slack notification steps
}
}
}Output
[Pipeline] echo
This stage will fail
[Pipeline] script
[Pipeline] error
Failing the build intentionally
[Pipeline] post
[Pipeline] echo
Build failed! Sending notification...
Common Pitfalls
Common mistakes when using post failure include:
- Placing
failureoutside thepostblock, which causes syntax errors. - Not using
error()or failing steps properly, so the failure block never triggers. - Expecting
failureto run on unstable builds; it only runs on actual failures.
groovy
pipeline {
agent any
stages {
stage('Test') {
steps {
echo 'This will not fail'
}
}
}
// Wrong: failure block outside post
// failure {
// echo 'This will cause a syntax error'
// }
post {
failure {
echo 'Correct place for failure block'
}
}
}Quick Reference
| Keyword | Description |
|---|---|
| post | Defines actions after pipeline stages complete |
| failure | Runs steps only if the build fails |
| success | Runs steps only if the build succeeds |
| always | Runs steps regardless of build result |
| unstable | Runs steps if the build is unstable |
Key Takeaways
Use the post { failure { ... } } block to run steps only when the build fails.
Place the failure block inside the post section to avoid syntax errors.
The failure block does not run on unstable builds, only on failures.
Common uses include sending notifications or cleaning up after failure.
Test your pipeline by forcing a failure to verify the failure block runs.