Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send Slack notification after Jenkins pipeline build failed?

I have a pipeline groovy script in Jenkins v2.19. Also I have a
"Slack Notification Plugin" v2.0.1 and "Groovy Postbuild Plugin".

I have successfully send a message "build started" and "build finished" (if it had).

When some build step failed – how I can send a message "Build failed" to the Slack channel?

like image 936
kivagant Avatar asked Aug 25 '16 08:08

kivagant


People also ask

How do I send a Slack notification?

From your desktop, click your profile picture in the top right. Select Preferences from the menu to open your notification preferences. Under Notify me about, choose your notification triggers.

How do I send Jenkins console to Slack?

Install Jenkins app for SlackSearch for “Jenkins CI” and click Add. You will be sent to the Jenkins app page in your browser. Click Install. Select the Slack channel you want to post to and click Add Jenkins CI integration.

What is slackSend in Jenkins?

slackSend : Send Slack Message Bot user option indicates the token belongs to a custom Slack app bot user in Slack. If the notification will be sent to a user via direct message, the default integration sends it via @slackbot, use this option if you want to send messages via a bot user. channel : String (optional)


1 Answers

You could do something like this and use a try catch block.

Here is some example Code:

node {     try {         notifyBuild('STARTED')          stage('Prepare code') {             echo 'do checkout stuff'         }          stage('Testing') {             echo 'Testing'             echo 'Testing - publish coverage results'         }          stage('Staging') {             echo 'Deploy Stage'         }          stage('Deploy') {             echo 'Deploy - Backend'             echo 'Deploy - Frontend'         }    } catch (e) {     // If there was an exception thrown, the build failed     currentBuild.result = "FAILED"     throw e   } finally {     // Success or failure, always send notifications     notifyBuild(currentBuild.result)   } }  def notifyBuild(String buildStatus = 'STARTED') {   // build status of null means successful   buildStatus =  buildStatus ?: 'SUCCESSFUL'    // Default values   def colorName = 'RED'   def colorCode = '#FF0000'   def subject = "${buildStatus}: Job '${env.JOB_NAME} [${env.BUILD_NUMBER}]'"   def summary = "${subject} (${env.BUILD_URL})"    // Override default values based on build status   if (buildStatus == 'STARTED') {     color = 'YELLOW'     colorCode = '#FFFF00'   } else if (buildStatus == 'SUCCESSFUL') {     color = 'GREEN'     colorCode = '#00FF00'   } else {     color = 'RED'     colorCode = '#FF0000'   }    // Send notifications   slackSend (color: colorCode, message: summary) } 

Complete snippet can be found here Jenkinsfile Template

like image 141
JamalMcCrackin Avatar answered Sep 28 '22 12:09

JamalMcCrackin