Jenkins - force exit pipeline when failure

1. Issue

In some specific cases, if we use try catch exception, Jenkins knows that issues, but still continue running other stage in pipeline. We need a force handling to make this pipeline failure immediately

2. Solution

currentBuild.result = 'FAILURE'
error("Failure right here, force exit")
stage("DB migration") {
  steps { script {
    slackSend (color: COLOR_MAP['SUCCESS'],
               channel: '#live-deployment',
               token: 'Fawxxxxxxxxxxxx',
               message: "*`STARTING`*: *core db migrating*, build #${env.BUILD_NUMBER}, <${env.BUILD_URL}|Go to this job>")
    try {
      withCredentials([usernamePassword(credentialsId: 'xxxxx-credential', usernameVariable: 'DB_USERNAME', passwordVariable: 'DB_PASSWORD')]) {
        withAWS(region:"eu-cexxxxxxx", credentials:"aws") {
          sh """
            packer build -force dbmigration/vm-db-migration.json
          """
        }
      }
    } catch (error) {
        slackSend (color: COLOR_MAP['FAILURE'],
                   channel: '#live-deployment',
                   token: 'Fawxxxxxxxxxxxx',
                   message: "*`FAILURE`*: *core db migrating*, build #${env.BUILD_NUMBER} \n${error}\n<${env.BUILD_URL}|Go to this job>")
        currentBuild.result = 'FAILURE'
        error("${error}")
    }
  }}
}

Last updated