Skip to main content

Get Azure Costs using Microsoft Azure Billing API

· 2 min read
Hasan Gural

In this article, we will try to gather consumption details using custom queries from Microsoft.CostManagement API on Azure. There are different ways to get these details but I will show you the simplest way to get this.

caution

First of all, you must have Enrollment reader access on Enterprise Agreement Blade. Othwerise you can't access the Billing Account API. Make sure that you have login to Azure PowerShell in order to get your access token using Get-AzAccessToken cmdlet

#region - Getting cost from Azure API For Billing Account 

$enrollmentNumber = "{enrollmentNumber}"

$authHeader = @{

'Authorization' = 'Bearer ' + (Get-AzAccessToken).Token

}

$body = @"
{
"type": "ActualCost",
"timeframe": "Custom",
"timePeriod": {
"from": "__from__",
"to": "__to__"
},
"dataSet": {
"granularity": "None",
"aggregation": {
"totalCostUSD": {
"name": "CostUSD",
"function": "Sum"
}
},
"sorting": [
{
"direction": "ascending",
"name": "UsageDate"
}
],
"grouping": [
{
"type": "Dimension",
"name": "SubscriptionId"
},
{
"type": "Dimension",
"name": "SubscriptionName"
}
]
}
}
"@

$cost = @();

$timeFrames = @(

[PSCustomObject]@{
"from" = "2022-01-01T00:00:00Z"
"to" = "2022-01-31T00:00:00Z"
"period" = "Jan"
},
[PSCustomObject]@{
"from" = "2022-02-01T00:00:00Z"
"to" = "2022-02-28T00:00:00Z"
"period" = "Feb"
}
)

ForEach($frame in $timeFrames) {

$updatedBody = $null;

$updatedBody = $body.Replace("__from__", $frame.from)
$updatedBody = $updatedBody.Replace("__to__", $frame.to)

Write-Output "[INFORMATION - Time frame is from:$($frame.from) "
Write-Output "[INFORMATION - Time frame is to:$($frame.to) "

$updatedBody ;

$getCosts = Invoke-RestMethod -Method Post -Headers $authHeader -ContentType "application/json" -Body $updatedBody `
-Uri "https://management.azure.com/providers/Microsoft.Billing/billingAccounts/$($enrollmentNumber)/providers/Microsoft.CostManagement/query?api-version=2021-10-01"

Start-Sleep -Seconds 60

ForEach($rw in $getCosts.properties.rows) {

$obj = [PSCustomObject]@{

CostUSD = $rw[0]
SubscriptionId = $rw[1]
SubscriptionName = $rw[2]
Month = $frame.period

}

$cost += $obj

}

}

If you could execute above PowerShell Script then you have it. Here is the your first communucation with the Cost Management Query API. Let me know for further examples.