-
Notifications
You must be signed in to change notification settings - Fork 41
/
index.js
executable file
·90 lines (81 loc) · 3.02 KB
/
index.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
var aws = require('aws-sdk');
var cwl = new aws.CloudWatchLogs();
var ses = new aws.SES();
exports.handler = function(event, context) {
var message = JSON.parse(event.Records[0].Sns.Message);
var alarmName = message.AlarmName;
var oldState = message.OldStateValue;
var newState = message.NewStateValue;
var reason = message.NewStateReason;
var requestParams = {
metricName: message.Trigger.MetricName,
metricNamespace: message.Trigger.Namespace
};
cwl.describeMetricFilters(requestParams, function(err, data) {
if(err) console.log('Error is:', err);
else {
console.log('Metric Filter data is:', data);
getLogsAndSendEmail(message, data);
}
});
};
function getLogsAndSendEmail(message, metricFilterData) {
var timestamp = Date.parse(message.StateChangeTime);
var offset = message.Trigger.Period * message.Trigger.EvaluationPeriods * 1000;
var metricFilter = metricFilterData.metricFilters[0];
var parameters = {
'logGroupName' : metricFilter.logGroupName,
'filterPattern' : metricFilter.filterPattern ? metricFilter.filterPattern : "",
'startTime' : timestamp - offset,
'endTime' : timestamp
};
cwl.filterLogEvents(parameters, function (err, data){
if (err) {
console.log('Filtering failure:', err);
} else {
console.log("===SENDING EMAIL===");
var email = ses.sendEmail(generateEmailContent(data, message), function(err, data){
if(err) console.log(err);
else {
console.log("===EMAIL SENT===");
console.log(data);
}
});
}
});
}
function generateEmailContent(data, message) {
var events = data.events;
console.log('Events are:', events);
var style = '<style> pre {color: red;} </style>';
var logData = '<br/>Logs:<br/>' + style;
for (var i in events) {
logData += '<pre>Instance:' + JSON.stringify(events[i]['logStreamName']) + '</pre>';
logData += '<pre>Message:' + JSON.stringify(events[i]['message']) + '</pre><br/>';
}
var date = new Date(message.StateChangeTime);
var text = 'Alarm Name: ' + '<b>' + message.AlarmName + '</b><br/>' +
'Runbook Details: <a href="http://wiki.mycompany.com/prodrunbook">Production Runbook</a><br/>' +
'Account ID: ' + message.AWSAccountId + '<br/>'+
'Region: ' + message.Region + '<br/>'+
'Alarm Time: ' + date.toString() + '<br/>'+
logData;
var subject = 'Details for Alarm - ' + message.AlarmName;
var emailContent = {
Destination: {
ToAddresses: ["Add destination email here"]
},
Message: {
Body: {
Html: {
Data: text
}
},
Subject: {
Data: subject
}
},
Source: 'Add source email here'
};
return emailContent;
}