AWS: Obtain BlendedCost billing data

There may be a case when you might want to use Get-CECostAndUsage Cmdlet, however I thought it might be helpful to document some examples. The AWS documentation doesn't display any example. Below is my attempt to come up with some examples, which I found useful for me, may be someone else does too.

 

Running the Cmdlet without any parameters, doesn’t reveal what we are looking for, so I checked the command reference: https://docs.aws.amazon.com/powershell/latest/reference/items/Get-CECostAndUsage.html. None of the parameters appear to be mandatory, still I got this error without any parameters:

"Time period is required"

 

I guessed period is DateInterval, so went ahead and created it for sample, but hit another parameter required error:

"Granularity can only be MONTHLY or DAILY"

I made sure again I provided Granularity, trying DAILY and hit another parameter 'metric' missing:

"Selected metrics cannot be null"

Valid values for metric are BlendedCost, UnblendedCost, UsageQuantity, NormalizedUsageAmount, AmortizedCost. I tried one of them and hit another error:

Sounds good so far, I had to enable cost explorer access to my user. So now I activated IAM user/role access to billing information https://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/grantaccess.html to grant my IAM user access to billing info. And here is the result:

I’m sure heading somewhere. After expanding the ResultsByTime object, I could eventually land to a result I was looking for that looked similar to the Cost Management Dashboard on the AWS console

Here is from the AWS web console billing home:

 

So, here is what I added to a script, so I get to know the cost for current month right away:

<Edit>

Please note, accessing Cost Explorer APIs are chargeable.

Reference: https://aws.amazon.com/aws-cost-management/pricing/

</Edit>

 

<Code>

 #Print cost details for the Account for current month
$currDate = Get-Date
$firstDay = Get-Date $currDate -Day 1 -Hour 0 -Minute 0 -Second 0
$lastDay = Get-Date $firstDay.AddMonths(1).AddSeconds(-1)
$firstDayFormat = Get-Date $firstDay -Format 'yyyy-MM-dd'
$lastDayFormat = Get-Date $lastDay -Format 'yyyy-MM-dd'

$interval = New-Object Amazon.CostExplorer.Model.DateInterval
$interval.Start = $firstDayFormat
$interval.End = $lastDayFormat

$costUsage = Get-CECostAndUsage -TimePeriod $interval -Granularity MONTHLY -Metric BlendedCost

$costUsage.ResultsByTime.Total["BlendedCost"]

</Code>