Stage 7 · Master
Cloud SDKs & Azure Automation
Azure SDK for Python
azure-identity, DefaultAzureCredential, and the azure-mgmt-* namespace.
Azure SDK Overview
The Azure SDK for Python is organized by service. Each service has a management package (azure-mgmt-*) for controlling resources and a data plane package for interacting with the service itself.
| Package | Purpose | Example |
|---|---|---|
| azure-identity | Authentication | DefaultAzureCredential, ClientSecretCredential |
| azure-mgmt-compute | VM management | Create, list, delete VMs |
| azure-mgmt-storage | Storage management | Storage accounts, containers |
| azure-mgmt-network | Networking | VNets, NSGs, load balancers |
| azure-keyvault-secrets | Key Vault data plane | Read/write secrets |
# Core identity library
pip install azure-identity
# Management libraries (pick what you need)
pip install azure-mgmt-compute
pip install azure-mgmt-storage
pip install azure-mgmt-network
pip install azure-mgmt-resource
# Data plane libraries
pip install azure-keyvault-secrets
pip install azure-storage-blobInstall only the packages you need. Each azure-mgmt-* package is a separate dependency. Do not install all of them at once.
Authentication with azure-identity
from azure.identity import DefaultAzureCredential
from azure.mgmt.compute import ComputeManagementClient
# DefaultAzureCredential tries multiple auth methods in order:
# 1. Environment variables (AZURE_CLIENT_ID, AZURE_TENANT_ID, AZURE_CLIENT_SECRET)
# 2. Managed Identity (when running on Azure)
# 3. Azure CLI credentials (for local development)
# 4. Azure PowerShell credentials
# 5. Interactive browser login (fallback)
credential = DefaultAzureCredential()
# Use with any management client
compute_client = ComputeManagementClient(
credential=credential,
subscription_id="your-subscription-id",
)DefaultAzureCredential works everywhere — local development, CI/CD, and production on Azure. It automatically selects the right auth method based on the environment.
from azure.identity import (
ClientSecretCredential,
ManagedIdentityCredential,
AzureCliCredential,
)
# Service principal with secret (for CI/CD)
cred = ClientSecretCredential(
tenant_id="your-tenant-id",
client_id="your-client-id",
client_secret="your-client-secret",
)
# Managed Identity (for Azure VMs, App Service, AKS)
cred = ManagedIdentityCredential(client_id="your-managed-identity-id")
# Azure CLI (for local development only)
cred = AzureCliCredential()Use DefaultAzureCredential for most cases. Use explicit credentials only when you need specific behavior, like a particular managed identity or service principal.
Management Clients
from azure.identity import DefaultAzureCredential
from azure.mgmt.compute import ComputeManagementClient
from azure.mgmt.resource import ResourceManagementClient
credential = DefaultAzureCredential()
subscription_id = "your-subscription-id"
# List all VMs across resource groups
compute_client = ComputeManagementClient(credential, subscription_id)
for vm in compute_client.virtual_machines.list_all():
print(f"{vm.name} ({vm.location})")
print(f" VM size: {vm.hardware_profile.vm_size}")
print(f" Admin: {vm.os_profile.admin_username}")
# List resources by type
resource_client = ResourceManagementClient(credential, subscription_id)
for resource in resource_client.resources.list():
if resource.type == "Microsoft.Compute/virtualMachines":
print(f"VM: {resource.name} in {resource.resource_group}")Management clients follow a consistent pattern: list, get, create, update, delete. The SDK handles pagination automatically.
Error Handling
from azure.identity import DefaultAzureCredential
from azure.mgmt.compute import ComputeManagementClient
from azure.core.exceptions import (
ResourceNotFoundError,
ResourceExistsError,
HttpResponseError,
)
credential = DefaultAzureCredential()
client = ComputeManagementClient(credential, "subscription-id")
try:
vm = client.virtual_machines.get("my-rg", "my-vm")
except ResourceNotFoundError:
print("VM does not exist")
except ResourceExistsError:
print("VM already exists")
except HttpResponseError as e:
print(f"Azure API error: {e.status_code} - {e.message}")
except Exception as e:
print(f"Unexpected error: {e}")Azure SDK raises specific exceptions for common errors. ResourceNotFoundError and ResourceExistsError are the most common. HttpResponseError covers all HTTP-level failures.
Async Clients
import asyncio
from azure.identity.aio import DefaultAzureCredential
from azure.mgmt.compute.aio import ComputeManagementClient
async def list_vms():
credential = DefaultAzureCredential()
client = ComputeManagementClient(credential, "subscription-id")
async for vm in client.virtual_machines.list_all():
print(f"{vm.name}: {vm.hardware_profile.vm_size}")
await client.close()
await credential.close()
asyncio.run(list_vms())Every Azure SDK management client has an async version. Use it when you need to manage many resources concurrently. Always close the credential and client when done.
Best Practices
- Use DefaultAzureCredential everywhere — it works in dev and production
- Never hardcode credentials — use environment variables or Managed Identity
- Install only the azure-mgmt-* packages you need
- Use async clients when managing many resources concurrently
- Handle ResourceNotFoundError and HttpResponseError explicitly
- Close async clients and credentials when done
- Use resource tags to track ownership and cost centers
Store subscription IDs, tenant IDs, and client IDs in environment variables or a config file. Never commit them to version control. They are not secrets but they are environment-specific.
Mark this lesson complete to store local progress and unlock a cleaner resume path the next time you visit.