Last active
April 29, 2020 06:26
-
-
Save PrashantBhatasana/c0a9c59e7cc6cdf6f4d449b41f394bfa to your computer and use it in GitHub Desktop.
This file contains hidden or 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
var AWS = require('aws-sdk'); | |
var url = require('url'); | |
var https = require('https'); | |
var util = require('util'); | |
const p = require('phin'); | |
var costexplorer = new AWS.CostExplorer(); | |
const reqURL = process.env.Slack_Webhook_url; | |
function getCurrentMonth() { | |
var nowdate = new Date(); | |
var monthStartDay = new Date(nowdate.getFullYear(), nowdate.getMonth(), 1); | |
var monthEndDay = new Date(nowdate.getFullYear(), nowdate.getMonth() + 1, 1); | |
const monthStartStr = monthStartDay.getFullYear() + "-" + ("0" + (monthStartDay.getMonth() + 1)).slice(-2) + "-" + ("0" + (monthStartDay.getDate())).slice(-2); | |
const monthEndStr = monthEndDay.getFullYear() + "-" + ("0" + (monthEndDay.getMonth() + 1)).slice(-2) + "-" + ("0" + (monthEndDay.getDate())).slice(-2); | |
return { | |
"Start": monthStartStr, | |
"End": monthEndStr | |
}; | |
} | |
async function notifySlack(blendedCost, NetblendedCost) { | |
var arrOfVals = getCurrentMonth(); | |
const message = { | |
'channel': process.env.Slack_Channel_name, | |
'username': 'AWS Billing', | |
'text': process.env.Account_name + '\n Date: ' + arrOfVals.Start + " - " + arrOfVals.End, | |
'icon_emoji': ':aws:', | |
'attachments': [{ | |
'color': '#8697db', | |
'fields': [ | |
{ | |
'title': 'Payable Amount (USD): ', | |
'value': "$" + blendedCost.Amount , | |
'short': true | |
}, | |
{ | |
'title': 'Spent Amount (USD): ', | |
'value': "$" + NetblendedCost.Amount, | |
'short': true | |
} | |
] | |
}] | |
}; | |
return p({ | |
url: reqURL, | |
method: 'POST', | |
data: message | |
}); | |
} | |
exports.handler = async (event, context, callback) => { | |
context.callbackWaitsForEmptyEventLoop = false; | |
console.log(getCurrentMonth()); | |
const data = await costexplorer.getCostAndUsage({ | |
TimePeriod: getCurrentMonth(), | |
Granularity: "MONTHLY", | |
Metrics: ["BlendedCost", "UnblendedCost", "UsageQuantity", "AmortizedCost", "NetAmortizedCost", "NetUnblendedCost", "NormalizedUsageAmount"], | |
Filter:{ | |
Dimensions: { | |
Key: 'RECORD_TYPE', | |
Values: [ | |
"Usage","Tax" | |
] | |
} | |
} | |
}).promise(); | |
console.log(data.ResultsByTime[0].Total); | |
console.log("Data:"+ JSON.stringify(data)); | |
const req = await notifySlack(data.ResultsByTime[0].Total.UnblendedCost, data.ResultsByTime[0].Total.BlendedCost); | |
return callback(null, { | |
BillFor: getCurrentMonth(), | |
CostTillDate: data.ResultsByTime[0].Total.BlendedCost | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment