Created
June 23, 2016 20:58
-
-
Save aelindeman/ee93e8c14fb687b7f4818baeee3dadff to your computer and use it in GitHub Desktop.
yet another CloudWatch-to-Slack AWS Lambda function
This file contains 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
const https = require('https'); | |
const url = require('url'); | |
const slack_url = ''; // put your slack webhook 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) { | |
context.fail(e.message); | |
}); | |
var payload = { | |
username: 'Amazon AWS' | |
}; | |
try { | |
var m = JSON.parse(rec.Sns.Message); | |
var color = | |
(m.NewStateValue.toLowerCase() == 'ok') ? '#2AB27B' : | |
(m.NewStateValue.toLowerCase() == 'alarm') ? '#F85900' : | |
'#E8E8E7'; | |
payload.text = '_Alarm status changed:_ ' + m.OldStateValue + ' → *' + m.NewStateValue + '*'; | |
payload.attachments = [ | |
{ | |
title_link: 'https://console.aws.amazon.com/cloudwatch/home', | |
title: m.AlarmDescription, | |
text: m.NewStateReason, | |
color: color, | |
footer: m.AlarmName + ' - ' + m.Trigger.Namespace, | |
ts: Math.round(parseInt(Date.parse(m.StateChangeTime)) / 1000), | |
fields: m.Trigger.Dimensions.map(function(i) { return { title: i.name, value: i.value, short: true }; }) | |
}, | |
]; | |
} catch (e) { | |
payload.text = rec.Sns.Message; | |
console.log(e); | |
} | |
req.write(JSON.stringify(payload)); | |
req.end(); | |
} | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment