Skip to content

Instantly share code, notes, and snippets.

@beatngu13
Last active July 13, 2022 21:58
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save beatngu13/c525e65bbf2ed4dbf10dfc1258152aea to your computer and use it in GitHub Desktop.
Save beatngu13/c525e65bbf2ed4dbf10dfc1258152aea to your computer and use it in GitHub Desktop.
Fancy notifications for Slack and HipChat in a scripted Jenkins pipeline
// 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
Copy link

Does this apply for a Declarative Pipeline too?

@beatngu13
Copy link
Author

@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