How to Use post {} Conditions in a Jenkins Pipeline
The post {} block runs steps after a stage or pipeline based on outcome: always, success, failure, unstable, or changed.
Add post {} at the pipeline or stage level. Each condition (like failure or always) holds steps that run only when that outcome applies, ideal for cleanup and alerts.
Outcome-based post steps
Cleanup always runs; the failure notification only fires when the build fails.
Jenkinsfile
pipeline {
agent any
stages {
stage('Build') {
steps { sh 'npm ci && npm run build' }
}
}
post {
always {
cleanWs()
}
success {
echo 'Build succeeded'
}
failure {
mail to: 'team@example.com',
subject: "Failed: ${env.JOB_NAME} #${env.BUILD_NUMBER}",
body: "See ${env.BUILD_URL}"
}
}
}Gotchas
alwaysruns no matter what; put workspace cleanup and artifact archiving there.changedruns only when the build result differs from the previous run, useful for status flips.- Stage-level
post {}scopes to that stage; pipeline-level scopes to the whole run.
Key takeaways
post {}runs steps by outcome: always, success, failure, etc.- Put cleanup and archiving under
always. - post can attach to a stage or the whole pipeline.
Related guides
How to Archive Artifacts in a Jenkins PipelineArchive build artifacts in a Jenkins declarative pipeline with archiveArtifacts, controlling fingerprinting,…
How to Publish JUnit Test Reports in a Jenkins PipelinePublish JUnit test reports in a Jenkins declarative pipeline with the junit step so test results, trends, and…