Created
February 2, 2021 10:13
-
-
Save sks147/fc759942d7cd6072723cf8bf341b2f2f to your computer and use it in GitHub Desktop.
Send Cloudwatch Alerts from SNS to slack
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
console.log('[Amazon CloudWatch Notification]'); | |
//Taken from https://raw.githubusercontent.com/ashiina/aws-lambda-cloudwatch-slack/master/handler.js | |
var ALARM_CONFIG = [ | |
{ | |
channel: "#cloudwatch-alerts", | |
mention: "<@here> ", | |
color: "#F35A00", | |
severity: "CRITICAL" | |
} | |
]; | |
var SLACK_CONFIG = { | |
path: "https://hooks.slack.com/services/xxxxxxxxxxx/yyyyyyyyyyy/xxxxxxxxxxxxxxxxxxxxx", | |
}; | |
var http = require ('https'); | |
var querystring = require ('querystring'); | |
exports.handler = function(event, context) { | |
// console.log(event.Records[0]); | |
// parse information | |
var message = event.Records[0].Sns.Message; | |
var subject = event.Records[0].Sns.Subject; | |
var timestamp = event.Records[0].Sns.Timestamp; | |
// vars for final message | |
var channel; | |
var severity; | |
var color; | |
// create post message | |
var alarmMessage = ""+ | |
"*Subject: "+subject+"*\n"+ | |
"Message: "+message+"\n"+ | |
"Timestamp: "+timestamp; | |
// check subject for condition | |
for (var i=0; i < ALARM_CONFIG.length; i++) { | |
var row = ALARM_CONFIG[i]; | |
alarmMessage = row.mention+" "+alarmMessage+" "; | |
channel = row.channel; | |
severity = row.severity; | |
color = row.color; | |
break; | |
} | |
if (!channel) { | |
context.done('error', "Invalid channel"); | |
} | |
var payloadStr = JSON.stringify({ | |
"attachments": [ | |
{ | |
"fallback": alarmMessage, | |
"text": alarmMessage, | |
"mrkdwn_in": ["text"], | |
"username": "AWS-CloudWatch-Lambda-bot", | |
"fields": [ | |
{ | |
"title": "Severity", | |
"value": severity, | |
"short": true | |
} | |
], | |
"color": color | |
} | |
], | |
"channel":channel | |
}); | |
var postData = querystring.stringify({ | |
"payload": payloadStr | |
}); | |
console.log(postData); | |
var options = { | |
hostname: "hooks.slack.com", | |
port: 443, | |
path: SLACK_CONFIG.path, | |
method: 'POST', | |
headers: { | |
'Content-Type': 'application/x-www-form-urlencoded', | |
'Content-Length': postData.length | |
} | |
}; | |
var req = http.request(options, function(res) { | |
// console.log("Got response: " + res.statusCode); | |
res.on("data", function(chunk) { | |
// console.log('BODY: '+chunk); | |
context.done(null, 'done!'); | |
}); | |
}).on('error', function(e) { | |
context.done('error', e); | |
}); | |
req.write(postData); | |
req.end(); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment