Microsoft Azure Commerce Management Client Library for Python

6.0.0 · active · verified Sat Apr 11

The azure-mgmt-commerce library provides a Python interface for managing Azure Commerce resources, primarily for retrieving usage details and rate card information via Azure Resource Manager (ARM) APIs. It is part of the broader Azure SDK for Python and is actively maintained with a regular release cadence. The current stable version is 6.0.0.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to authenticate with Azure using `DefaultAzureCredential`, create a `UsageManagementClient`, and then retrieve daily usage aggregates and rate card information for your Azure subscription. Ensure you have the `AZURE_SUBSCRIPTION_ID` environment variable set and appropriate Azure permissions (e.g., Reader role on the subscription).

import os
from datetime import date, timedelta
from azure.identity import DefaultAzureCredential
from azure.mgmt.commerce import UsageManagementClient

# Set your Azure Subscription ID
# You can set this as an environment variable or replace directly
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 or replace 'YOUR_SUBSCRIPTION_ID' in the code.")
else:
    try:
        # Authenticate using DefaultAzureCredential (supports various auth methods)
        credential = DefaultAzureCredential()

        # Create a CommerceManagementClient
        commerce_client = UsageManagementClient(credential, subscription_id)

        # Get usage aggregates for the last day
        end_date = date.today()
        start_date = end_date - timedelta(days=1)

        print(f"Retrieving usage aggregates from {start_date} to {end_date}...")
        usage_iterator = commerce_client.usage_aggregates.list(
            str(start_date) + 'T00:00:00Z',
            str(end_date) + 'T00:00:00Z'
        )

        print("\nDaily Usage Aggregates:")
        for item in usage_iterator:
            print(f"  Resource: {item.properties.meter_details.meter_name}, Quantity: {item.properties.quantity}, Unit: {item.properties.unit_of_measure}")

        # Example: Get Rate Card for a specific offer and region
        # OfferDurableID example: 'MS-AZR-0062P' for Pay-As-You-Go
        # This query string needs to be carefully constructed based on desired filters
        # For available OfferDurableIDs, refer to Azure documentation
        # Example query string for a specific offer, currency, locale, and region
        rate_card_query = "OfferDurableId eq 'MS-AZR-0062P' and Currency eq 'USD' and Locale eq 'en-US' and RegionInfo eq 'US'"

        print(f"\nGetting rate card for: {rate_card_query}")
        rate_card = commerce_client.rate_card.get(rate_card_query)

        if rate_card.meters:
            print("First 3 Rate Card Meters (if available):")
            for i, meter in enumerate(rate_card.meters):
                if i >= 3: break
                print(f"  Meter: {meter.meter_name}, Unit: {meter.unit}, Tiered Rates: {meter.meter_rates}")
        else:
            print("No meters found in the rate card for the given query.")

    except Exception as e:
        print(f"An error occurred: {e}")

view raw JSON →