How to Use Post Success in Jenkins Pipeline
In Jenkins Pipeline, use the
post block with the success condition to run steps only when the pipeline completes successfully. Place your commands inside post { success { ... } } to execute them after a successful build.Syntax
The post block in a Jenkins Pipeline defines actions that run after the main pipeline stages. The success condition inside post runs its steps only if the pipeline finishes without errors.
- post: Defines post-build actions.
- success: Runs steps only on successful pipeline completion.
- Steps inside
successare executed after all stages complete successfully.
groovy
pipeline {
agent any
stages {
stage('Example') {
steps {
echo 'Running main pipeline steps'
}
}
}
post {
success {
echo 'This runs only if the pipeline succeeds'
}
}
}Example
This example shows a simple Jenkins Pipeline with a post block using success. The message inside success prints only if the pipeline finishes without errors.
groovy
pipeline {
agent any
stages {
stage('Build') {
steps {
echo 'Building the project'
}
}
stage('Test') {
steps {
echo 'Running tests'
}
}
}
post {
success {
echo 'Pipeline succeeded! Sending notification.'
}
}
}Output
[Pipeline] echo
Pipeline succeeded! Sending notification.
Common Pitfalls
Common mistakes when using post success include:
- Placing
postinsidestagesinstead of at the pipeline level. - Using
successwithout apostblock. - Expecting
successto run if some stages fail (it only runs if the entire pipeline succeeds).
Always ensure post is at the pipeline root and success is inside it.
groovy
/* Wrong placement example */ pipeline { agent any stages { stage('Build') { steps { echo 'Build step' } post { success { echo 'This will cause an error' } } } } } /* Correct placement example */ pipeline { agent any stages { stage('Build') { steps { echo 'Build step' } } } post { success { echo 'This runs after successful pipeline' } } }
Quick Reference
| Keyword | Description |
|---|---|
| post | Defines actions to run after pipeline stages |
| success | Runs steps only if pipeline completes successfully |
| failure | Runs steps only if pipeline fails |
| always | Runs steps regardless of pipeline result |
| unstable | Runs steps if pipeline is unstable |
Key Takeaways
Use the post block at the pipeline root to define post-build actions.
Place success inside post to run steps only after a successful pipeline.
Do not put post blocks inside individual stages; it causes errors.
Post success steps do not run if any stage fails or the pipeline errors.
Use post success to send notifications or clean up only on success.