-
-
Save yyolk/258a1e2ffc619569bece to your computer and use it in GitHub Desktop.
AWS Lambda function for forwarding SNS notifications to Slack
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
console.log('Loading function'); | |
const https = require('https'); | |
const url = require('url'); | |
// to get the slack hook url, go into slack admin and create a new "Incoming Webhook" integration | |
const slack_url = 'https://hooks.slack.com/services/...'; | |
const slack_req_opts = url.parse(slack_url); | |
slack_req_opts.method = 'POST'; | |
slack_req_opts.headers = {'Content-Type': 'application/json'}; | |
const pp = function(o) { | |
return JSON.stringify(o, null, 2); | |
} | |
exports.handler = function(event, context) { | |
(event.Records || []).forEach(function (rec) { | |
if (rec.Sns) { | |
var emoji = ":mailbox_with_mail:"; // default for icon_emoji | |
var username = rec.Sns.TopicArn; // use TopicArn as username | |
var parsed = {}; | |
var text = ""; | |
var req = https.request(slack_req_opts, function (res) { | |
if (res.statusCode === 200) { | |
context.succeed('posted to slack'); | |
} else { | |
context.fail('status code: ' + res.statusCode); | |
} | |
}); | |
req.on('error', function(e) { | |
console.log('problem with request: ' + e.message); | |
context.fail(e.message); | |
}); | |
try { | |
parsed = JSON.parse(rec.Sns.Message); | |
// since we just want to see the JSON; | |
// surrond json in code snippet brackets | |
text = '```' + pp(parsed) + '```'; | |
// Parse the CloudWatch alarm message, set emoji based on that state | |
// TODO: only post the StateValue and AlarmName to keep it clean. | |
if (parsed.NewStateValue) { | |
switch (parsed.NewStateValue){ | |
case "ALARM": | |
emoji = ":alarm_clock:"; | |
break; | |
case "OK": | |
emoji = ":white_check_mark:"; | |
break; | |
case "INSUFFICIENT_DATA": | |
emoji = ":information_source:"; | |
break; | |
} | |
// use if you have frequent alarms... | |
// text = emoji+"\n"+text; | |
// or change the username to force icon_emoji to change | |
// username = username + " " + parsed.NewStateValue; | |
} | |
} | |
catch(e) { | |
parsed = {}; | |
// if sns message is a string, just show it | |
text = rec.Sns.Message; | |
} | |
// send the request, with the payload as the body | |
req.write(JSON.stringify({ | |
text: text, | |
username: username, | |
icon_emoji: emoji | |
})); | |
req.end(); | |
} | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
renamed
function.js
toindex.js
to match default handler for lambda ofindex.handler