Skip to content

Instantly share code, notes, and snippets.

@jowrjowr
Created March 31, 2020 16:01
Show Gist options
  • Save jowrjowr/662debf637782021556783d9797e0f8b to your computer and use it in GitHub Desktop.
Save jowrjowr/662debf637782021556783d9797e0f8b to your computer and use it in GitHub Desktop.
slack alert
var https = require('https');
var util = require('util');
exports.handler = function(event, context) {
console.log(JSON.stringify(event, null, 2));
// the SNS message contains the actual details of importance
// which is always going to be json from guard duty and cloudwatch
// should only parse one message at a time?
var message = JSON.parse(event.Records[0].Sns.Message);
var subject = event.Records[0].Sns.Subject;
var postData = {
"channel": process.env.SLACK_CHANNEL,
"username": process.env.SLACK_USERNAME,
"icon_emoji": ":fire:"
};
var publish = true;
// severity doesn't do anything really until valid html color codes
// are generated from these values. slack doesn't understand "good" color.
// TBD on anyone caring.
var severity = "good";
// slack docu on attachments
// https://api.slack.com/messaging/composing/layouts#attachments
if ("AlarmName" in message) {
// cloudwatch
if (!subject.includes("prod")) {
publish = false;
}
// construct the slack message
postData.text = "*" + subject + "*";
postData.attachments = [{
"color": severity,
"fields": [
{
"title": "Alarm Description",
"value": message.AlarmDescription,
"short": false
},
{
"title": "Region",
"value": message.Region,
"short": true
},
{
"title": "Alarm",
"value": message.AlarmName,
"short": true
},
{
"title": "Time",
"value": message.StateChangeTime,
"short": true
},
]
}];
} else if ("source" in message) {
// not sure what else uses this form
if (message.source == "aws.guardduty") {
// definitely guard duty
severity = message.detail.severity;
subject = message["detail-type"] + ": " + message.detail.title;
// construct the slack message
postData.text = "*" + subject + "*";
postData.attachments = [{
"color": severity,
"fields": [
{
"title": "Resource Type",
"value": message.detail.resource.resourceType,
"short": true
},
{
"title": "Action",
"value": message.detail.service.action.actionType,
"short": true
},
{
"title": "Region",
"value": message.detail.region,
"short": true
},
{
"title": "Time",
"value": message.time,
"short": true
},
]
}];
}
}
var options = {
method: 'POST',
hostname: 'hooks.slack.com',
port: 443,
path: process.env.SLACK_HOOK_PATH
};
if (publish == true) {
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();
} else {
console.log('not a production error. discarding.');
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment