How to Use post always in Jenkins Pipeline
In Jenkins Pipeline, use the
post block with the always condition to run steps after every build, no matter if it succeeds, fails, or is aborted. Place the post { always { ... } } block inside your pipeline or stage to ensure cleanup or notifications always run.Syntax
The post block defines actions that run after the main pipeline or stage steps. The always condition inside post ensures the enclosed steps run regardless of build outcome.
Structure:
post: Starts the post-build actions block.always: Runs steps no matter if the build succeeded, failed, or was aborted.- Steps inside
always: Commands or scripts to execute after the build.
groovy
pipeline {
agent any
stages {
stage('Example') {
steps {
echo 'Running main steps'
}
}
}
post {
always {
echo 'This runs after every build'
}
}
}Example
This example shows a Jenkins Pipeline that prints a message during the build and always prints a final message after the build finishes, no matter the result.
groovy
pipeline {
agent any
stages {
stage('Build') {
steps {
echo 'Building the project'
// Simulate a failure by uncommenting the next line
// error 'Build failed!'
}
}
}
post {
always {
echo 'Cleaning up resources or sending notifications'
}
}
}Output
[Pipeline] echo
Building the project
[Pipeline] echo
Cleaning up resources or sending notifications
Common Pitfalls
- Placing
postblock outside thepipelineblock causes syntax errors. - Using
alwaysinsidestepsinstead ofpostis invalid. - Not including
postblock means no guaranteed cleanup or notifications.
Correct usage ensures cleanup or notifications run every time.
groovy
/* Wrong: post block outside pipeline */ post { always { echo 'This will cause an error' } } /* Right: post block inside pipeline */ pipeline { agent any stages { stage('Test') { steps { echo 'Testing' } } } post { always { echo 'Runs always after build' } } }
Quick Reference
Use the post block with these conditions:
| Condition | When It Runs |
|---|---|
always | Every build, success or failure |
success | Only if build succeeds |
failure | Only if build fails |
unstable | Build is unstable |
changed | Build status changed from previous |
| Condition | When It Runs |
|---|---|
| always | Every build, success or failure |
| success | Only if build succeeds |
| failure | Only if build fails |
| unstable | Build is unstable |
| changed | Build status changed from previous |
Key Takeaways
Use the post { always { ... } } block inside your pipeline to run steps after every build.
The always condition runs regardless of build success, failure, or abort.
Place the post block inside the pipeline block to avoid syntax errors.
Common uses include cleanup, notifications, and resource release.
Other post conditions like success or failure run only on specific build results.