Chatwithcloud logo

ChatWithCloud

AWS GenAI Tools

Get the Total Cost of AWS CloudWatch for The Current Month Using JavaScript and AWS SDK

Code

In our JavaScript code, we are using the AWS SDK to make a request to the AWS Cost Explorer service. This request will return the unblended cost for the current month for the AWS CloudWatch service.

const AWS = require('aws-sdk'); const costExplorer = new AWS.CostExplorer(); let startOfMonth = new Date(new Date().getFullYear(), new Date().getMonth(), 1) .toISOString() .split('T')[0]; let endOfMonth = new Date().toISOString().split('T')[0]; const params = { TimePeriod: { Start: startOfMonth, End: endOfMonth }, Granularity: 'MONTHLY', Metrics: ['UnblendedCost'], Filter: { Dimensions: { Key: 'SERVICE', Values: ['Amazon CloudWatch'] } } }; costExplorer.getCostAndUsage(params, function(err, data) { if (err) console.log(err, err.stack); else console.log(data.ResultsByTime[0].Total.UnblendedCost); });

Detailed Code Explanation

In our code, we first import the aws-sdk module and initialize the AWS.CostExplorer() function without passing in any parameters.

Next, we define the startOfMonth and endOfMonth variables to set the date range for our cost calculation. We use the JavaScript Date object methods to get the first and last day of the current month.

Then we define the params object that will be passed into the getCostAndUsage() method of AWS cost explorer service.

Finally, we call the getCostAndUsage() method with our parameters. This returns a promise, and when the promise resolves, we console.log() the cost of AWS CloudWatch for the current month.

What's The Expected Output Format

The output will be a JSON object containing the unblended cost for the AWS CloudWatch service for the current month.

{ "Amount": "String", "Unit": "String" }

Considerations & caveats Section

Be aware that the getCostAndUsage() method in our code returns costs based on the UnblendedCost metric. This means that the cost returned does not include credits, upfront RI fees, taxes, and other adjustments that affect the final charge.

The code also assumes that the AWS SDK has been configured with valid AWS credentials.

Required IAM permissions and Example Policy

The IAM user executing this script needs access to the AWS Cost Explorer service. You should assign the ViewBilling policy to allow it.

Here's an example policy:

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

FAQ

Q1. Why am I getting AccessDeniedException: User: is not authorized to perform: ce:GetCostAndUsage with an explicit deny error?

This error occurs when the user does not have permission to make requests to the AWS Cost Explorer API. You should ensure that the IAM policy attached to your user or role includes permissions for the ce:GetCostAndUsage action.

Q2. Can I query the cost of other AWS services using this code?

Yes, you can query the cost of any other AWS service. Just replace Amazon CloudWatch in the Values list within the Filter object with the name of the service whose cost you want to query.

Q3. Can I specify a different time range?

Yes, you can customize the time range by modifying the Start and End properties of the TimePeriod object.

Q4. Why are the costs reported by this script different from my AWS bill?

The script reports the UnblendedCost, which is the cost before any discounts, credits, or other adjustments. Your final AWS bill may be less due to these factors.





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