Skip to content

Instantly share code, notes, and snippets.

@JD10NN3
Last active August 6, 2021 05:28
Show Gist options
  • Save JD10NN3/e8f84f7062d02248120c5494a09f26e2 to your computer and use it in GitHub Desktop.
Save JD10NN3/e8f84f7062d02248120c5494a09f26e2 to your computer and use it in GitHub Desktop.
Example of a External Jenkins Pipeline triggers configuration that send notification to Teams
/*
This is used as part of a dynamic Jenkins pipeline configuration.
You can reference to this Gist for more details:
https://gist.github.com/JD10NN3/7796639e4d427d474c172d5e6b0fa49a
*/
import groovy.json.JsonOutput
import groovy.json.JsonSlurperClassic
import javax.mail.Address
import javax.mail.Session
import javax.mail.Message
import javax.mail.Transport
import javax.mail.internet.MimeMessage
import javax.mail.internet.InternetAddress
// Empty mapping, since that script is only used as a simplified example
// Take a look at the following link for more details
// https://gist.github.com/JD10NN3/5de45a5c9b75c25c81da107acdda34c8
this.triggersMapping = []
/**
* The default/fallback configuration
* Those triggers are called only if there is not existing triggers
* mapping for a specific branch.
*/
this.defaultTriggersMapping = [
"on_approval" : { target ->
// Example of usage:
// - Send a MS Teams notification on the CICD Channel to notify about a waiting deployment approval
// and use the target argument to provide a better context within the notification content.
// to master with a checklist for every commits to test.
// To avoid spamming the Teams channel we consider this
// pipeline if no more recent jobs are currently running.
def nextBuild = currentBuild.getNextBuild()
if(nextBuild == null) {
// The content of the notification to appear on Teams.
def content = """<p>Pipeline waiting for an approval to deploy on <b>${target.env.toUpperCase()}</b>. Click <b><a href=\"${env.RUN_DISPLAY_URL}\">here</a></b> for more details.</p>
<small>(you have ~30 minutes to proceed)</small>"""
def changes = ""
build = currentBuild
// We loop until we get all jobs that failed to run.
while(build != null && build.result.toString() != "SUCCESS" && build.result.toString() != "UNSTABLE" || currentBuild.number == build.number) {
for (changeLog in build.changeSets) {
for(entry in changeLog.items) {
def item = entry.msg
// Replace Jira and GitHub PullRequest with their respective links
item = item.replaceAll(/(ISSUE-[0-9]{4})/, "<a href=\"https://[jira_link]/browse/\$1\">\$1</a>")
item = item.replaceAll(/#([0-9]{4})/, "<a href=\"https://github.com/JD10NN3/monbudget-react-app/pull/\$1\">#\$1</a>")
// Create an HTML list for better rendering in Teams.
changes += "<li>${item}</li>"
}
}
build = build.previousBuild
}
if(changes != "") {
content += "<ul>${changes}</ul>"
}
sendTeamsNotification("Action Required", content)
}
}
]
/**
* Call the specified trigger for a specific branch
* @param trigger name of the targeted trigger
* @param branch name of the targeted branch
* @return default or specific mapping based on branch name provided
*/
def callTriggerOnBranch(trigger, branch) {
return this.callTriggerOnBranchWithArgs(trigger, branch, null)
}
/**
* Call the specified trigger for a specific branch with arguments
* @param trigger name of the targeted trigger
* @param branch name of the targeted branch
* @param args arguments to pass to a trigger
* @return default or specific mapping based on branch name provided
*/
def callTriggerOnBranchWithArgs(trigger, branch, args) {
triggers = this.triggersMapping.getOrDefault(branch, defaultTriggersMapping)
return triggers.getOrDefault(trigger, this.defaultTriggersMapping[trigger]).call(args)
}
/**
* Send a notification to the CI/CD Pipeline Teams channel
* @param subject The subject of the notification
* @param content The content of the notification
*/
def sendTeamsNotification(subject, content) {
def descriptor = Jenkins.instance.getDescriptor("hudson.tasks.Mailer")
Session session = descriptor.createSession();
MimeMessage msg = new MimeMessage(session);
// Get the Administrator email configured inside Jenkins
InternetAddress fromAddress = new InternetAddress(descriptor.getAdminAddress());
msg.setFrom(fromAddress)
// We set the Teams channel email as the recipient
// How to get that email: https://support.office.com/en-us/article/send-an-email-to-a-channel-in-teams-d91db004-d9d7-4a47-82e6-fb1b16dfd51e#bkmk_send
msg.setRecipients(
Message.RecipientType.TO,
(InternetAddress[]) [new InternetAddress('[teams_id].onmicrosoft.com@ca.teams.ms')].toArray()
);
// Add the subject and content for our notification
// and make sure to the "html" format for better rendering.
String charset = descriptor.getCharset();
msg.setSubject(subject, charset);
msg.setText(content, charset, "html")
// Let's send our call for action
Transport transporter = session.getTransport("smtp");
transporter.connect();
transporter.send(msg);
}
return this
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment