How to Run Steps on Success or Failure in a Jenkins Pipeline
The post section runs steps based on build outcome - success, failure, unstable, always, and more.
Add a post {} block at pipeline or stage scope. Each condition (success, failure, always, cleanup) runs after the main steps depending on the result.
Outcome-based post blocks
The post section sends success/failure notifications and always cleans up the workspace.
Jenkinsfile
pipeline {
agent any
stages {
stage('Test') {
steps {
sh 'npm ci && npm test'
}
}
}
post {
success {
sh './notify.sh "build passed"'
}
failure {
sh './notify.sh "build FAILED"'
}
always {
junit 'reports/**/*.xml'
cleanWs()
}
}
}Gotchas
postruns after the stages/pipeline complete - use it for notifications and cleanup, not main work.unstable(e.g. failing tests viajunit) is distinct fromfailure; handle both if you treat test failures as unstable.- A pipeline-level
postruns once for the whole build; a stage-levelpostruns per stage - pick the right scope.
Related guides
How to Run a Job Only When a Previous Job Succeeds or Fails in CircleCIOrder CircleCI jobs with requires so a job runs only after another succeeds, and run cleanup or alerting rega…
How to Post a Slack Notification from a Jenkins PipelinePost a Slack notification from a Jenkins pipeline with the Slack Notification plugin slackSend step in a post…