Azure - Create Cost Management dashboard using LogAnalytics

 

Introduction

The cost management module in Azure is the one of most used interms of checking on the cost utilization.  This Cost Management delivers the nice GUI to see the like Resource Group, Region, Service Name, Tag & Etc.. Also, we can see assign Permissions to users who're in need of checking cost for the respective workloads and the available permissions are Cost Management Reader, Owner & Contributor.

But recently i have been asked to create a cost management dashboard for the project owners where they have multiple Resource Groups and some projects spread across with different Subscriptions with necessary tags added. 

I see some complications in dashboard because if anyone having multiple Resource Groups based permissions, they may not be able to published dashboards as the Cost Management feature is scoped at subscription level. 

So to mitigate this issue, we can use LogAnalytics API to upload the costs and use the Kusto Query to publish the costs. 

The below script can be used in Azure Automation -> Runbooks which will be scheduled to run Every day, Month so that it'll be uploaded and can be showcased in Dashboard.

########Script Starts here##################

$servicePrincipalConnection = Get-AutomationConnection -Name AzureRunAsConnection   

$params = @{
    ServicePrincipal      = $true
    TenantId              = $servicePrincipalConnection.TenantId
    ApplicationId         = $servicePrincipalConnection.ApplicationId
    CertificateThumbprint = $servicePrincipalConnection.CertificateThumbprint 
}
Add-AzAccount @params 

$sub = Get-AzSubscription -SubscriptionName "Subscription Name"
Select-AzSubscription -Subscription $sub | Out-Null

$PretaxCost = 0
$BillArrays = @()
$TotalCost = 0


$BillArrays=Get-AzConsumptionUsageDetail -StartDate 12-01-2021 -EndDate 12-01-2021 | ConvertTo-Json # Get 1 day cost and this can be automated to get everyday costs as well.


$CustomerId = "LogAnalytics ID"
$SharedKey = "LogAnalytics Key"
$StringToSign = "POST" + "`n" + $BillArrays.Length + "`n" + "application/json" + "`n" + $("x-ms-date:" + [DateTime]::UtcNow.ToString("r")) + "`n" + "/api/logs"
$BytesToHash = [Text.Encoding]::UTF8.GetBytes($StringToSign)
$KeyBytes = [Convert]::FromBase64String($SharedKey)
$HMACSHA256 = New-Object System.Security.Cryptography.HMACSHA256
$HMACSHA256.Key = $KeyBytes
$CalculatedHash = $HMACSHA256.ComputeHash($BytesToHash)
$EncodedHash = [Convert]::ToBase64String($CalculatedHash)
$Authorization = 'SharedKey {0}:{1}' -f $CustomerId$EncodedHash

$Uri = "https://" + $CustomerId + ".ods.opinsights.azure.com" + "/api/logs" + "?api-version=2016-04-01"
$Headers = @{
    "Authorization"        = $Authorization;
    "Log-Type"             = "AzCostLog";
    "x-ms-date"            = [DateTime]::UtcNow.ToString("r");
    "time-generated-field" = $(Get-Date)
}
$Response = Invoke-WebRequest -Uri $Uri -Method Post -ContentType "application/json" -Headers $Headers -Body $BillArrays -UseBasicParsing
if ($Response.StatusCode -eq 200) {
    Write-Information -MessageData "Logs are Successfully Stored in Log Analytics Workspace" -InformationAction Continue
}

########Script Ends here##################

The above script uploads the cost in Azure LogAnalytics in AzCostLog table and it might take around 15-30min initially to upload all the logs
for the mentioned date.

Once it's upload then it can be customized further using the Kusto query.

The below sample dashboard I have created for this demonstration.





















I believe this will definitely help you to design your cost management dashboard.

Comments