Azure Management Consumption Client Library for Python

10.0.0 · active · verified Sat Apr 11

This is the Microsoft Azure Consumption Client Library. It allows programmatic management of consumption resources for Azure Enterprise Subscriptions, providing APIs to retrieve usage details, budgets, reservations, and other cost management data. The library is currently at version 10.0.0 and receives regular updates as part of the broader Azure SDK for Python.

Warnings

Install

Imports

Quickstart

This quickstart initializes the ConsumptionManagementClient using `DefaultAzureCredential` and lists the first 10 usage details for a specified subscription. Ensure `AZURE_SUBSCRIPTION_ID` and other Azure authentication environment variables (e.g., `AZURE_CLIENT_ID`, `AZURE_CLIENT_SECRET`, `AZURE_TENANT_ID`) are set for `DefaultAzureCredential` to work. The example includes a basic filter for a specific month.

import os
from azure.identity import DefaultAzureCredential
from azure.mgmt.consumption import ConsumptionManagementClient

# Set your Azure Subscription ID as an environment variable or replace directly
# For example: export AZURE_SUBSCRIPTION_ID="<your-subscription-id>"
subscription_id = os.environ.get("AZURE_SUBSCRIPTION_ID", "")

if not subscription_id:
    raise ValueError("AZURE_SUBSCRIPTION_ID environment variable not set.")

# Authenticate using DefaultAzureCredential
# This will try several authentication methods, including environment variables,
# managed identity, Visual Studio Code, Azure CLI, etc.
credential = DefaultAzureCredential()

# Create a client for the Azure Consumption Management
client = ConsumptionManagementClient(credential, subscription_id)

print(f"Listing usage details for subscription: {subscription_id}")

# List usage details for the current subscription
# 'scope' is typically '/subscriptions/{subscriptionId}' or '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}'
# For simplicity, we'll use the subscription scope.
scope = f"/subscriptions/{subscription_id}"

# Iterate through the usage details (adjust filter if needed)
# Note: For MCA (Microsoft Customer Agreement) subscriptions, historical data might be limited.
# See warnings for more details.
for usage_detail in client.usage_details.list(scope=scope, expand="meterDetails,additionalProperties", filter="properties/usageEnd ge '2026-03-01' and properties/usageEnd le '2026-03-31'", top=10):
    print(f"  Resource: {usage_detail.resource_id.split('/')[-1]} | Date: {usage_detail.usage_start} - {usage_detail.usage_end} | Cost: {usage_detail.pretax_cost} {usage_detail.currency}")

print("Successfully listed some usage details.")

view raw JSON →