Skip to content

Instantly share code, notes, and snippets.

@welbesw
Created October 1, 2018 16:10
Show Gist options
  • Save welbesw/baa36f55f0b87821021f93095513a466 to your computer and use it in GitHub Desktop.
Save welbesw/baa36f55f0b87821021f93095513a466 to your computer and use it in GitHub Desktop.
Lambda function to get current month cost summary
var AWS = require('aws-sdk');
exports.handler = (event, context, callback) => {
var now = new Date();
var startDate = new Date(now.getFullYear(), now.getMonth(), 1);
var endDate = new Date(now.getFullYear(), now.getMonth() + 1, 1)
if (now.getMonth() == 12) {
endDate = new Date(now.getFullYear() + 1, 1, 1)
}
var start = startDate.toISOString().slice(0, 10);
var end = endDate.toISOString().slice(0, 10)
var params = {
"TimePeriod" : {
"Start" : start,
"End" : end
},
"Granularity" : "MONTHLY",
"Metrics" : ["AmortizedCost"]
}
var costexplorer = new AWS.CostExplorer();
costexplorer.getCostAndUsage(params, function (err, data) {
if (err) {
console.log(err, err.stack); // an error occurred
callback(err);
}
else {
console.log(data); // successful response
var amount = parseFloat(data["ResultsByTime"][0]["Total"]["AmortizedCost"]["Amount"])
var amountCurrency = "$" + amount.toFixed(2)
const response = {
"statusCode": 200,
"body": JSON.stringify({ "amount": amountCurrency, "start" : start, "end" : end }),
"isBase64Encoded": false
};
callback(null, response);
}
});
};
@junkangli
Copy link

Date.getMonth() returns an integer between 0 - 11. 0 corresponds to January, 1 to February, and so on. Therefore, the condition to check whether the month now is December should be

if (now.getMonth() == 11) {

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment