Monitor Monthly AWS Spend on Elgato Stream Deck

I recently developed a custom plugin for my Elgato Stream Deck device, which can display my current AWS spend. This is accomplished by using a purely PowerShell-based plugin, in conjunction with the AWS Tools for PowerShell REST API wrapper. The AWS Cost Explorer service updates your monthly AWS spend approximately once every 24 hours, according to the documentation, so you aren’t going to get precise information, down to the minute. That being said, there is an optional feature in AWS Cost Explorer that will provide hourly details about your AWS spend. If you enable this option, there is an added cost for the higher level of granularity.

Although there is tons of boilerplate code that talks websockets to the Stream Deck software, the heart of this plugin lies in its use of the AWS Tools for PowerShell to interact with the AWS REST APIs. In particular, there is a PowerShell command called Get-CECostAndUsage, which exposes estimated AWS spend. The reason I say “estimated” is because your final bill is not calculated until each month has fully closed.

In order to properly invoke the Get-CECostAndUsage command, you’ll need to specify an Amazon.CostExplorer.Model.DateInterval object for the -TimePeriod parameter, which is part of the AWS SDK. If the AWS.Tools.CostExplorer module is not imported, this type will not be available. Essentially we just want to figure out what the first day of the month is, and the last day of the month, and use those values on our DateInterval object.

$Interval = [Amazon.CostExplorer.Model.DateInterval]::new()
$Interval.Start = (Get-date -Day 1).ToString('yyyy-MM-dd')
$Interval.End = (Get-Date -Day 1).AddMonths(1).AddDays(-1).ToString('yyyy-MM-dd')
$Cost = Get-CECostAndUsage -Metric UnblendedCost -TimePeriod $Interval -Granularity MONTHLY -ProfileName cbt -Region us-west-2
$MonthlyCost = '${0:0.##}' -f ([double]$Cost.ResultsByTime[0].Total.UnblendedCost.Amount)

Calling out to the AWS Cost Explorer APIs too many times can result in high costs. Hence, my Stream Deck plugin caches the data locally and displays it from the cache. There are probably other ways of optimizing the plugin performance, but right now it works just fine. Yesterday, I created the plugin, and this morning it had updated with the latest data from AWS Cost Explorer. That’s a good enough test, right?

Code for this module is stored on GitHub. You can download and use the module under the MIT license.

If you found this article interesting, check out my AWS automation training course at CBT Nuggets! We also have a free learner account with access to a limited set of our content library.