forked from ashiina/aws-lambda-cloudwatch-slack
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathhandler.js
114 lines (103 loc) · 2.33 KB
/
handler.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
console.log('[Amazon CloudWatch Notification]');
/*
configuration for each condition.
add any conditions here
*/
var ALARM_CONFIG = [
{
condition: "INFO",
channel: "#test",
mention: " ",
color: "#FF9F21",
severity: "INFO"
},
{
condition: "CRITICAL",
channel: "#general",
mention: "<@channel> ",
color: "#F35A00",
severity: "CRITICAL"
}
];
var SLACK_CONFIG = {
path: "YOUR_PATH",
};
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 = " *[Amazon CloudWatch Notification]* \n"+
"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];
console.log(row);
if (subject.match(row.condition)) {
console.log("Matched condition: "+row.condition);
alarmMessage = row.mention+" "+alarmMessage+" ";
channel = row.channel;
severity = row.severity;
color = row.color;
break;
}
}
if (!channel) {
console.log("Could not find condition.");
context.done('error', "Invalid condition");
}
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();
};