Amazon Relational Database Service(RDS) is a Cloud-based distributed relational database service. In today’s blog, I will share a script to generate RDS billing report for each RDS instance for a specified date range.
Before we start, we need to setup our AWS credentials and AWS Powershell SDK . Refer following documents to set those :
- https://docs.aws.amazon.com/powershell/latest/userguide/specifying-your-aws-credentials.html
- https://aws.amazon.com/powershell/
Here is the complete script you need to generate a CSV billing report of RDS resources in your account for a specified date range.
Param(
[Parameter(Mandatory=$false)]
[String]$firstDay,
[Parameter(Mandatory=$false)]
[String]$lastDay
)
#Print cost details for the Account for previous month
if([String]::IsNullOrEmpty($firstDay)){
$firstDay = Get-Date -Year (Get-Date).Year -Month (Get-Date).AddMonths(-1).Month -Day 1 -UFormat "%Y-%m-%d"
}
if([String]::IsNullOrEmpty($lastDay)){
$lastDay = Get-Date -Year (Get-Date).Year -Month (Get-Date).AddMonths(-1).Month -Day ([DateTime]::DaysInMonth((Get-Date).Year, (Get-Date).Month)) -UFormat "%Y-%m-%d"
}
$currentDir = $(Get-Location).Path
$oFile = "$($currentDir)\aws_rds_billing_usage_data.csv"
$tFile = "$($currentDir)\aws_rds_billing_usage_data_temp.csv"
if(Test-Path $oFile){
Remove-Item $oFile -Force
}
if(Test-Path $tFile){
Remove-Item $tFile -Force
}
Import-Module AWSPowershell
"Name,Date,UsageHours,Cost" | Out-File $tFile -Append -Encoding ASCII
$interval = New-Object Amazon.CostExplorer.Model.DateInterval
$interval.Start = $firstDay
$interval.End = $lastDay
$dimension = New-Object Amazon.CostExplorer.Model.DimensionValues
$dimension.Key = "SERVICE"
$dimension.Values ="Amazon Relational Database Service"
$Filter = New-Object Amazon.CostExplorer.Model.Expression
$Filter.Dimensions = $dimension
$groupInfo = New-Object Amazon.CostExplorer.Model.GroupDefinition
$groupInfo.Type = "TAG"
$groupInfo.Key = "Name"
$metric = @("BlendedCost","UsageQuantity")
####
$costUsage = Get-CECostAndUsage -TimePeriod $interval -Granularity DAILY -Metric $metric -Filter $Filter -GroupBy $groupInfo
ForEach($c in $costUsage.ResultsByTime){
$sTime = $cost = $rdsName = ""
$sTime = $c.TimePeriod.Start
ForEach($grp in $c.Groups){
$rdsName = $grp.Keys.Split("$")[1]
if([String]::IsNullOrEmpty($rdsName)){$rdsName = "No Name Tag"}
$cost = $grp.Metrics["BlendedCost"].Amount
$usageHours = $grp.Metrics["UsageQuantity"].Amount
"$rdsName,$sTime,$usageHours,$cost" | Out-File $tFile -Append -Encoding ASCII
}
}
Import-Csv $tFile | Sort-Object 'Name','Date' | Export-Csv -Path $oFile -NoTypeInformation
if(Test-Path $tFile){
Remove-Item $tFile -Force
}