-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.js
88 lines (62 loc) · 2.79 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
const AWS = require('aws-sdk');
const moment = require("moment");
const { IncomingWebhook } = require('@slack/webhook');
const currencyRound=function(num) {
return Math.round(Number.parseFloat(num)*100)/100;
}
exports.handler = function(event, context) {
console.log('start: ' + moment().format('YYYY-MM-DD hh:mm:ss.SSS'));
var aws_config = {
apiVersion: '2017-10-25',
accessKeyId : process.env.AWS_ACCESSKEY,
secretAccessKey : process.env.AWS_SECRET_ACCESSKEY,
region : 'us-east-1'
};
var returnval = 0;
const slack_webhook_url=process.env.SLACK_WEBHOOK_URL;
const awsCostExplorer = new AWS.CostExplorer(aws_config);
var now = new Date();
var monthFirst=moment(now).startOf('month').format('YYYY-MM-DD');
var monthLast=moment(now).endOf('month').format('YYYY-MM-DD');
var monthNextFirst=moment(now).endOf('month').add(1,"d").format('YYYY-MM-DD');
var monthTomorrow=moment(now).add(1,"day").format('YYYY-MM-DD');
var monthToday=moment(now).format('YYYY-MM-DD');
// https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/CostExplorer.html#getCostForecast-property
var params = {
Granularity: 'MONTHLY', /* required */
Metric: 'UNBLENDED_COST', /* required */
TimePeriod: { /* required */
End: monthLast, /* required */
Start: monthTomorrow /* required */
},
PredictionIntervalLevel: 51
};
const messagePrefix = process.env.COSTEXPLODER_MSGPREFIX || false;
awsCostExplorer.getCostForecast(params, function(err, data) {
var returnval=0;
console.log("in awsCOstExplorer");
if (err) {
console.log(err, err.stack); // an error occurred
} else {
console.log(data); // successful response
returnval=data.Total.Amount;
//console.log(data.Total.Amount);
var textmessage = (messagePrefix || 'Cost estimate until end of the month: ') + "\n\rMean: " + data.Total.Unit + " " + currencyRound(data.Total.Amount);
if(data.ForecastResultsByTime && data.ForecastResultsByTime[0] && data.ForecastResultsByTime[0].PredictionIntervalLowerBound && data.ForecastResultsByTime[0].PredictionIntervalUpperBound) {
textmessage = textmessage + "\n\r";
textmessage = textmessage + "Min: " + data.Total.Unit + " " + currencyRound(data.ForecastResultsByTime[0].PredictionIntervalLowerBound);
textmessage = textmessage + "\n\r";
textmessage = textmessage + "Max: " + data.Total.Unit + " " + currencyRound(data.ForecastResultsByTime[0].PredictionIntervalUpperBound);
}
const webhook = new IncomingWebhook(slack_webhook_url);
(async () => {
await webhook.send({
text: textmessage,
});
})();
}
return returnval;
});
console.log('end: ' + moment().format('YYYY-MM-DD hh:mm:ss.SSS'));
return context.logStreamName;
}