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?
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.
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.
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)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With