Created
October 1, 2018 16:10
-
-
Save welbesw/baa36f55f0b87821021f93095513a466 to your computer and use it in GitHub Desktop.
Lambda function to get current month cost summary
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'); | |
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); | |
} | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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 monthnow
is December should be