Microsoft Azure Resource Graph Client Library for Python

8.0.1 · active · verified Sat Apr 11

The `azure-mgmt-resourcegraph` library is the Microsoft Azure Resource Graph Client Library for Python. It provides an efficient way to query Azure resources across subscriptions and tenants at scale using Kusto Query Language (KQL). This package is currently active, with version 8.0.1 being the latest stable release as of November 2025, and is tested with Python 3.9+.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to query Azure resources using `ResourceGraphClient` and `DefaultAzureCredential`. It retrieves the ID, name, type, and location of the first 5 resources in a specified Azure subscription. Ensure `AZURE_SUBSCRIPTION_ID` and appropriate authentication environment variables (e.g., `AZURE_CLIENT_ID`, `AZURE_TENANT_ID`, `AZURE_CLIENT_SECRET`) are set.

import os
from azure.identity import DefaultAzureCredential
from azure.mgmt.resourcegraph import ResourceGraphClient

# Set your Azure subscription ID in an environment variable or replace directly
subscription_id = os.environ.get('AZURE_SUBSCRIPTION_ID', 'YOUR_AZURE_SUBSCRIPTION_ID')

def main():
    if subscription_id == 'YOUR_AZURE_SUBSCRIPTION_ID':
        print("Please set the AZURE_SUBSCRIPTION_ID environment variable or replace 'YOUR_AZURE_SUBSCRIPTION_ID' in the code.")
        return

    # Authenticate using DefaultAzureCredential. It tries multiple credential types.
    # Ensure AZURE_CLIENT_ID, AZURE_TENANT_ID, AZURE_CLIENT_SECRET (for service principal)
    # or AZURE_USERNAME, AZURE_PASSWORD (for interactive login) are set as environment variables
    # or use 'az login' for Azure CLI credential.
    credential = DefaultAzureCredential()

    # Create ResourceGraphClient
    client = ResourceGraphClient(credential)

    # Define your Kusto Query Language (KQL) query
    query_request = {
        "query": "Resources | project id, name, type, location | limit 5",
        "subscriptions": [subscription_id]
    }

    print(f"Running query on subscription: {subscription_id}")
    try:
        response = client.resources(query_request)
        for resource in response.data:
            print(f"ID: {resource['id']}, Name: {resource['name']}, Type: {resource['type']}, Location: {resource['location']}")
    except Exception as e:
        print(f"An error occurred: {e}")

if __name__ == '__main__':
    main()

view raw JSON →