Skip to content
Latchkey

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

  • post runs after the stages/pipeline complete - use it for notifications and cleanup, not main work.
  • unstable (e.g. failing tests via junit) is distinct from failure; handle both if you treat test failures as unstable.
  • A pipeline-level post runs once for the whole build; a stage-level post runs per stage - pick the right scope.

Related guides

Run this faster and cheaper on Latchkey managed runners. Start free →