Skip to content

Instantly share code, notes, and snippets.

@yyolk
Forked from vgeshel/function.js
Last active September 29, 2018 02:28
Show Gist options
  • Save yyolk/258a1e2ffc619569bece to your computer and use it in GitHub Desktop.
Save yyolk/258a1e2ffc619569bece to your computer and use it in GitHub Desktop.
AWS Lambda function for forwarding SNS notifications to Slack
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();
}
});
};
@yyolk
Copy link
Author

yyolk commented Aug 21, 2015

several improvements, more robust message handling

  • used emoji parsing via JeffRausch/function.js
  • uses icon_emoji to show the alarm state
  • defaults to trying to parse the Ss.Message but fall backs to
    sending the message as a string (so it doesn’t show up with double
    quotes a la (JSON.stringify(“some string”));

@yyolk
Copy link
Author

yyolk commented Aug 21, 2015

renamed function.js to index.js to match default handler for lambda of index.handler

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