Chatwithcloud logo

ChatWithCloud

AWS GenAI Tools

Get AWS Billing Details by Service for the Last Month Using JavaScript

This article is dedicated to demonstrating how you can fetch your AWS billing details, broken down by service for the last month, using JavaScript.

Code

const AWS = require('aws-sdk'); let costexplorer = new AWS.CostExplorer({}); let params = { TimePeriod: { Start: new Date(new Date().getFullYear(), new Date().getMonth() - 1, 1).toISOString().split('T')[0], End: new Date(new Date().getFullYear(), new Date().getMonth(), 0).toISOString().split('T')[0] }, Granularity: 'MONTHLY', Metrics: ['UnblendedCost'], GroupBy: [{Type: 'DIMENSION', Key: 'SERVICE'}] }; costexplorer.getCostAndUsage(params).promise() .then(data => ({ serviceCosts: data.ResultsByTime[0].Groups.map(group => ({ service: group.Keys[0], cost: group.Metrics.UnblendedCost.Amount}) )})).then(console.log) .catch(console.error);

Detailed Code Explanation

In this code, we're establishing a connection with AWS Cost Explorer Service using the AWS SDK. We have a specific set of parameters params that define the details we want:

Then, getCostAndUsage method of the CostExplorer service is called and with provided parameters. The response, after mapping through the Groups array, returns an array of objects that each contains the AWS service name and the cost of usage for that service over the last month. The result is then logged in the console.

Expected Output Format

The console output will be in JSON format, where each object in serviceCosts array represents a certain AWS service and the unblended cost for using this service. Here is a simplified example:

{ "serviceCosts": [ { "service": "Amazon S3", "cost": "35.00" }, { "service": "Amazon EC2", "cost": "75.00" }, ... ] }

Considerations & Caveats

Required IAM Permissions and Example Policy

The IAM permissions required include ce:GetCostAndUsage.

{ "Version": "2012-10-17", "Statement": [{ "Sid": "VisualEditor0", "Effect": "Allow", "Action": "ce:GetCostAndUsage", "Resource": "*" }] }

Frequently Asked Questions

Q: Can I modify the code to fetch the cost for services over a different period?

A: Yes, you can modify the Start and End dates in the TimePeriod parameters in the code.

Q: What does 'UnblendedCost' mean?

A: Unblended cost represents the cost of all AWS services without applying any discounts like AWS Savings Plans or Reserved Instances.

Q: Can I fetch the cost segregated according to AWS regions?

A: Yes. Modify the GroupBy parameter to { "Type": "DIMENSION", "Key": "REGION" }.

Q: What if I don't have IAM permissions to access CostExplorer?

A: Without proper IAM permissions, AWS SDK will not be able to fetch cost and usage data. Please ensure that the AWS account you're using has ce:GetCostAndUsage permission.





Related articles
Monitor and Notify When Approaching Service LimitsGet Current IAM Identity TypeScriptCalculate the Size of Each S3 Bucket and Find the One with the Most Data