Skip to content

Instantly share code, notes, and snippets.

@dschaaff
Created February 9, 2018 18:18
Show Gist options
  • Star 13 You must be signed in to star a gist
  • Fork 9 You must be signed in to fork a gist
  • Save dschaaff/bd3275c1395a48cef1a82708d3a55f5d to your computer and use it in GitHub Desktop.
Save dschaaff/bd3275c1395a48cef1a82708d3a55f5d to your computer and use it in GitHub Desktop.
jenkins pipeline library for slack notifications with nice formatting
#!/usr/bin/env groovy
/**
* notify slack and set message based on build status
*/
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import hudson.tasks.test.AbstractTestResultAction;
import hudson.model.Actionable;
def call(String buildStatus = 'STARTED', String channel = '#jenkins') {
// buildStatus of null means successfull
buildStatus = buildStatus ?: 'SUCCESSFUL'
channel = channel ?: '#jenkins'
// Default values
def colorName = 'RED'
def colorCode = '#FF0000'
def subject = "${buildStatus}: Job '${env.JOB_NAME} [${env.BUILD_NUMBER}] (<${env.RUN_DISPLAY_URL}|Open>) (<${env.RUN_CHANGES_DISPLAY_URL}| Changes>)'"
def title = "${env.JOB_NAME} Build: ${env.BUILD_NUMBER}"
def title_link = "${env.RUN_DISPLAY_URL}"
def branchName = "${env.BRANCH_NAME}"
def commit = sh(returnStdout: true, script: 'git rev-parse HEAD')
def author = sh(returnStdout: true, script: "git --no-pager show -s --format='%an'").trim()
def message = sh(returnStdout: true, script: 'git log -1 --pretty=%B').trim()
// Override default values based on build status
if (buildStatus == 'STARTED') {
color = 'YELLOW'
colorCode = '#FFFF00'
} else if (buildStatus == 'SUCCESSFUL') {
color = 'GREEN'
colorCode = 'good'
} else if (buildStatus == 'UNSTABLE') {
color = 'YELLOW'
colorCode = 'warning'
} else {
color = 'RED'
colorCode = 'danger'
}
// get test results for slack message
@NonCPS
def getTestSummary = { ->
def testResultAction = currentBuild.rawBuild.getAction(AbstractTestResultAction.class)
def summary = ""
if (testResultAction != null) {
def total = testResultAction.getTotalCount()
def failed = testResultAction.getFailCount()
def skipped = testResultAction.getSkipCount()
summary = "Test results:\n\t"
summary = summary + ("Passed: " + (total - failed - skipped))
summary = summary + (", Failed: " + failed + " ${testResultAction.failureDiffString}")
summary = summary + (", Skipped: " + skipped)
} else {
summary = "No tests found"
}
return summary
}
def testSummaryRaw = getTestSummary()
// format test summary as a code block
def testSummary = "```${testSummaryRaw}```"
println testSummary.toString()
JSONObject attachment = new JSONObject();
attachment.put('author',"jenkins");
attachment.put('author_link',"https://danielschaaff.com");
attachment.put('title', title.toString());
attachment.put('title_link',title_link.toString());
attachment.put('text', subject.toString());
attachment.put('fallback', "fallback message");
attachment.put('color',colorCode);
attachment.put('mrkdwn_in', ["fields"])
// JSONObject for branch
JSONObject branch = new JSONObject();
branch.put('title', 'Branch');
branch.put('value', branchName.toString());
branch.put('short', true);
// JSONObject for author
JSONObject commitAuthor = new JSONObject();
commitAuthor.put('title', 'Author');
commitAuthor.put('value', author.toString());
commitAuthor.put('short', true);
// JSONObject for branch
JSONObject commitMessage = new JSONObject();
commitMessage.put('title', 'Commit Message');
commitMessage.put('value', message.toString());
commitMessage.put('short', false);
// JSONObject for test results
JSONObject testResults = new JSONObject();
testResults.put('title', 'Test Summary')
testResults.put('value', testSummary.toString())
testResults.put('short', false)
attachment.put('fields', [branch, commitAuthor, commitMessage, testResults]);
JSONArray attachments = new JSONArray();
attachments.add(attachment);
println attachments.toString()
// Send notifications
slackSend (color: colorCode, message: subject, attachments: attachments.toString(), channel: channel)
}
@ziyanakthar
Copy link

Hello @dschaaff

I am having hard time making this code as a shared library so that I take common elements as a base structure to include in slack message with following items which can be used for all the jobs loading the slack code as shared library so that we have a common code for adding slack notification part.

  1. Tests summary
  2. Git commit changes
  3. Git authors
  4. Build results

This code does not seem to be working, can you please advise.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment