Skip to content

Instantly share code, notes, and snippets.

@membrive
Created January 23, 2019 17:03
Show Gist options
  • Save membrive/d92a07ca86350dee7c76921457f30437 to your computer and use it in GitHub Desktop.
Save membrive/d92a07ca86350dee7c76921457f30437 to your computer and use it in GitHub Desktop.
Lambda function to send SNS notifications to Slack.
const https = require('https');
const url = require('url');
const slack_url = 'https://hooks.slack.com/services/SET_YOUR_SERVICE_URL'; // set your service URL here
const slack_req_opts = url.parse(slack_url);
slack_req_opts.method = 'POST';
slack_req_opts.headers = {
'Content-Type': 'application/json'
};
exports.handler = function(event, context) {
(event.Records || []).forEach(function(rec) {
if (rec.Sns) {
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);
});
var text_msg = JSON.stringify(rec.Sns.Message, null, ' ');
try {
var msg_data = [];
var parsed = JSON.parse(rec.Sns.Message);
for (var key in parsed) {
msg_data.push(key + ': ' + parsed[key]);
}
text_msg = msg_data.join("\n");
} catch (e) {
console.log(e);
}
if (parsed.NewStateValue == 'OK') {
var params = {
attachments: [{
fallback: text_msg,
pretext: rec.Sns.Subject,
color: "#59A452",
fields: [{
"value": text_msg,
"short": false
}]
}]
};
} else {
var params = {
attachments: [{
fallback: text_msg,
pretext: rec.Sns.Subject,
color: "#D00000",
fields: [{
"value": text_msg,
"short": false
}]
}]
};
}
req.write(JSON.stringify(params));
req.end();
}
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment