Last active
July 13, 2022 21:58
-
-
Save beatngu13/c525e65bbf2ed4dbf10dfc1258152aea to your computer and use it in GitHub Desktop.
Fancy notifications for Slack and HipChat in a scripted Jenkins pipeline
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Based on https://jenkins.io/blog/2016/07/18/pipeline-notifications/. | |
def notifyMessengers(String buildStatus = 'STARTED') { | |
// Build status of null means successful. | |
buildStatus = buildStatus ?: 'SUCCESS' | |
// Replace encoded slashes. | |
def decodedJobName = env.JOB_NAME.replaceAll("%2F", "/") | |
def colorSlack | |
def colorHipchat | |
if (buildStatus == 'STARTED') { | |
colorSlack = '#D4DADF' | |
colorHipchat = 'GRAY' | |
} else if (buildStatus == 'SUCCESS') { | |
colorSlack = '#BDFFC3' | |
colorHipchat = 'GREEN' | |
} else if (buildStatus == 'UNSTABLE') { | |
colorSlack = '#FFFE89' | |
colorHipchat = 'YELLOW' | |
} else { | |
colorSlack = '#FF9FA1' | |
colorHipchat = 'RED' | |
} | |
def msgSlack = "${buildStatus}: `${decodedJobName}` #${env.BUILD_NUMBER}: ${env.BUILD_URL}" | |
def msgHipchat = "${buildStatus}: <code>${decodedJobName}</code> #${env.BUILD_NUMBER}: <a href=\"${env.BUILD_URL}\">${env.BUILD_URL}</a>" | |
slackSend(color: colorSlack, message: msgSlack) | |
hipchatSend(color: colorHipchat, message: msgHipchat) | |
} | |
node { | |
try { | |
notifyMessengers() | |
// Existing build steps. | |
} catch (e) { | |
currentBuild.result = "FAILURE" | |
throw e | |
} finally { | |
notifyMessengers(currentBuild.result) | |
} | |
} |
@ericklarac only scripted pipelines allow the direct use of Groovy syntax such as a try-catch block. In declarative pipelines, you can use post
to come up with a similar solution, check out the Jenkins documentation on "Cleaning up and notifications" or Liam Newman's follow-up post "Declarative Pipeline: Notifications and Shared Libraries".
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Does this apply for a Declarative Pipeline too?