Azure Compute Management Client Library for Python
The `azure-mgmt-compute` library is the Microsoft Azure Compute Management Client Library for Python, providing essential functionality for managing Azure compute resources like Virtual Machines, Virtual Machine Scale Sets, Disks, and Galleries. It enables developers to create, configure, manage, and scale Windows and Linux virtual machines programmatically. Currently at version 37.2.0, the library is actively maintained with frequent updates, often on a monthly or bi-monthly release cadence, reflecting ongoing development in the Azure platform.
Warnings
- breaking The library no longer includes API version subfolders (e.g., `v20xx_xx_xx` modules) and only targets the latest API-Version available on Azure. Importing models via `client.models` is also removed.
- breaking The authentication mechanism for Azure SDKs was redesigned. Older versions used `ServicePrincipalCredentials` from `azure.common`, which is no longer supported.
- breaking All query and header parameters are now keyword-only, enforcing more explicit function calls.
- gotcha `ModuleNotFoundError: No module named 'azure.profiles'` can occur if `azure-common` is an older version than expected by `azure-mgmt-compute`.
- gotcha Intermittent `DeserializationError` can occur when retrieving VM details, sometimes linked to API version mismatches or unexpected responses.
- gotcha Resource and cost management can be challenging. Unmonitored or over-provisioned resources lead to unexpected Azure bills.
Install
-
pip install azure-mgmt-compute azure-identity
Imports
- ComputeManagementClient
from azure.mgmt.compute import ComputeManagementClient
- DefaultAzureCredential
from azure.identity import DefaultAzureCredential
- models
from azure.mgmt.compute import models
Quickstart
import os
from azure.identity import DefaultAzureCredential
from azure.mgmt.compute import ComputeManagementClient
# Set environment variables for authentication and subscription ID
# AZURE_CLIENT_ID, AZURE_TENANT_ID, AZURE_CLIENT_SECRET
# AZURE_SUBSCRIPTION_ID
subscription_id = os.getenv("AZURE_SUBSCRIPTION_ID", "")
if not subscription_id:
print("Please set the AZURE_SUBSCRIPTION_ID environment variable.")
exit(1)
# Authenticate using DefaultAzureCredential (looks for env vars, managed identity, etc.)
credential = DefaultAzureCredential()
# Create a Compute Management Client
compute_client = ComputeManagementClient(credential, subscription_id)
try:
# List all virtual machines in the subscription
print("Listing all virtual machines:")
for vm in compute_client.virtual_machines.list_all():
print(f"- VM Name: {vm.name}, Location: {vm.location}")
except Exception as e:
print(f"An error occurred: {e}")
print("Ensure you have set AZURE_SUBSCRIPTION_ID and have appropriate permissions.")