Oct 02 2024 12:09 AM
Hi,
We have multiple azure subscriptions in directory. How to export the Cost summary by for all subscriptions at once with tags?
I would like to automatically export / send the costs for the past month for all subscriptions including tags. Possible?
Thanks for hints.
Roman
Oct 02 2024 08:08 AM
(A) Using Export - Create Export via GUI or cli (given below) and schedule it to run every month
az costmanagement export create --name MonthlyExport --type Usage --scope "/subscriptions/{subscriptionId}" --storage-account-id {storageAccountId} --storage-container {containerName} --timeframe MonthToDate --storage-directory {directoryName}
(B) or, use Powershell to create a script (and schedule)
Install-Module -Name Az
Install-Module -Name AzCostTools
Connect-AzAccount
$arrCost = Get-SubscriptionCost -IncludeTags
now, the variable $arrCost, you can either choose to save it somewhere using Export-Csv command or use Send-Mail to email it to a group.
Also, Connect-Azaccount part has to be automated. you will have to save password in Automation Account or key vault and fetch during script execution. I have not included that part.
Recommendation is to use a service principal account with least privileged required. Here is the code:
Connect-AzAccount -ServicePrincipal -TenantId $tenantId -ApplicationId $appID -Credential (ConvertTo-SecureString $clientSecret -AsPlainText -Force
if you save it in automation account then
Import-Module Az.Accounts
$credential = Get-AutomationPSCredential -Name "MyStoredCredential"
Connect-AzAccount -Credential $credential
Oct 02 2024 05:24 PM - edited Oct 02 2024 05:25 PM
Below script for your reference, please make sure you fully understand before apply to your environment:
az costmanagement export create --name MonthlyExport --type Usage --scope "/subscriptions/{subscription-id}" --storage-account-id "/subscriptions/{subscription-id}/resourceGroups/{resource-group}/providers/Microsoft.Storage/storageAccounts/{storage-account}" --storage-container "costreports" --timeframe MonthToDate --storage-directory "monthlyreports"
Oct 03 2024 11:51 AM
You can export the monthly cost summary for all Azure subscriptions in a tenant automatically using Azure Cost Management APIs or Azure CLI commands.
Here's a simple Azure CLI command to achieve this:
For more information, refer to the Microsoft documentation:
Azure Cost Management APIs:
https://learn.microsoft.com/en-us/rest/api/cost-management/
https://learn.microsoft.com/en-us/rest/api/consumption/
Azure CLI commands for cost management:
https://learn.microsoft.com/en-us/cli/azure/costmanagement?view=azure-cli-latest
https://learn.microsoft.com/en-us/azure/cost-management-billing/automate/get-usage-data-azure-cli
Hope this helps you.
Many Thanks
Balasubramani.M
Oct 07 2024 12:18 AM