Skip to content

Instantly share code, notes, and snippets.

@jamtur01
Created February 4, 2017 17:41
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jamtur01/1ab379fe9fd2af1181b7e8f018430670 to your computer and use it in GitHub Desktop.
Save jamtur01/1ab379fe9fd2af1181b7e8f018430670 to your computer and use it in GitHub Desktop.
var https = require('https');
var util = require('util');
var webhook = '/services/webhook';
var errorMessage = "ERROR";
exports.handler = function(event, context) {
console.log(JSON.stringify(event, null, 2));
console.log('From SNS:', event.Records[0].Sns.Message);
var postData = {
"channel": "#monitoring",
"icon_emoji": ":cloud:",
};
var message = JSON.parse(event.Records[0].Sns.Message);
postData.attachments = [{
"text": message.Description,
"title": "AWS ASG Notifications",
"color": getStatusColor(message.Event),
}];
try {
postData.attachments[0]["fields"] = [];
for (var key of ['AutoScalingGroupName', 'Cause', 'Event', 'EC2InstanceId', 'Progress', 'StartTime']) {
var field = {
title: key,
value: message[key],
short: false
};
postData.attachments[0]["fields"].push(field);
}
} catch (err) {
console.log("Message body was not a JSON payload");
}
var options = {
method: 'POST',
hostname: 'hooks.slack.com',
port: 443,
path: webhook
};
var req = https.request(options, function(res) {
res.setEncoding('utf8');
res.on('data', function (chunk) {
context.done(null);
});
});
req.on('error', function(e) {
console.log('problem with request: ' + e.message);
});
req.write(util.format("%j", postData));
req.end();
};
String.prototype.contains = function(str, ignoreCase) {
return (ignoreCase ? this.toUpperCase() : this)
.indexOf(ignoreCase ? str.toUpperCase() : str) >= 0;
};
/* returns a Slack color depending on the modulus event type. Crash should be red, deploy should be
* green, and everything else will be orange.
*/
var getStatusColor = function(messageEvent) {
if(messageEvent.contains(errorMessage)) {
return 'danger';
} else {
return 'warning';
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment