Azure Cost Management Client Library

4.0.1 · active · verified Tue Apr 14

The Microsoft Azure Cost Management Client Library for Python allows developers to manage Azure cost and usage data programmatically. It provides access to features like querying cost data, managing budgets, and working with dimensions and exports. Currently at version 4.0.1, it follows the Azure SDK release cadence, with updates often tied to new API versions and general SDK guidelines.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to authenticate with Azure using `DefaultAzureCredential` and then list existing budgets within a specified Azure subscription using the `CostManagementClient`. Ensure you have the `AZURE_SUBSCRIPTION_ID` environment variable set, and your Azure credentials configured (e.g., via `az login` or environment variables like `AZURE_CLIENT_ID`, `AZURE_CLIENT_SECRET`, `AZURE_TENANT_ID`).

import os
from azure.identity import DefaultAzureCredential
from azure.mgmt.costmanagement import CostManagementClient

# Set your Azure Subscription ID from environment variables
subscription_id = os.environ.get("AZURE_SUBSCRIPTION_ID", "YOUR_SUBSCRIPTION_ID")

if subscription_id == "YOUR_SUBSCRIPTION_ID":
    print("Please set the AZURE_SUBSCRIPTION_ID environment variable.")
else:
    try:
        # Authenticate using DefaultAzureCredential (looks for env vars, managed identity, etc.)
        credential = DefaultAzureCredential()

        # Create a CostManagementClient
        client = CostManagementClient(credential, subscription_id)

        # Example: List budgets for the subscription
        print(f"Listing budgets for subscription: {subscription_id}")
        scope = f"subscriptions/{subscription_id}"
        budgets = client.budgets.list(scope=scope)
        
        found_budgets = False
        for budget in budgets:
            print(f"  Budget Name: {budget.name}, Amount: {budget.amount} {budget.currency}")
            found_budgets = True
        
        if not found_budgets:
            print("  No budgets found for this subscription.")

    except Exception as e:
        print(f"An error occurred: {e}")
        print("Ensure you have set up Azure credentials (e.g., AZURE_CLIENT_ID, AZURE_CLIENT_SECRET, AZURE_TENANT_ID) or are logged in via `az login`.")

view raw JSON →