Azure CLI
The Azure CLI is a set of command-line tools provided by Microsoft for managing Azure resources. While it is a Python-based application, it is primarily intended to be used as a shell command (`az`) rather than directly imported as a Python library in application code. It offers commands for data-plane and control-plane operations. The current version is 2.85.0, with frequent monthly releases.
Warnings
- gotcha The `azure-cli` PyPI package is the source for the command-line tool, but end-users are strongly advised to install it via official installers (e.g., `apt`, `yum`, `brew`, MSI) or the install script, rather than `pip install`. `pip install azure-cli` is primarily for developers, CI/CD, or highly isolated environments where pathing and dependencies must be managed carefully, and may not automatically set up the `az` executable on the system PATH.
- breaking Azure CLI continuously updates its Python version requirements. Starting with 2.49.0, Python >=3.10 is required. For 2.61.0+, Python >=3.11 is required. Newer versions have incrementally dropped support for older Python versions (e.g., Python 3.7 support dropped in 2.40.0, Python 3.8 dropped for versions requiring 3.10+). Ensure your Python environment meets the minimum requirement for your Azure CLI version.
- gotcha Azure CLI is a command-line tool, not a Python SDK. Do not attempt to `import azure.cli` to interact with Azure resources from your Python application. For programmatic interaction with Azure services, use the dedicated `azure-sdk-for-python` libraries (e.g., `azure-mgmt-storage`, `azure-identity`, `azure-storage-blob`). The `azure-cli` components are for extending the CLI itself or for internal operations.
- deprecated The `--json` output option has been deprecated in favor of `--output json` (or `-o json`). While `--json` might still work for some commands, `az` strongly recommends using the standard `--output` or `-o` parameter for consistency.
- breaking The `az feedback` command was removed in Azure CLI 2.50.0. This command was used to provide feedback directly to the Azure CLI team.
Install
-
pip install azure-cli -
curl -sL https://aka.ms/InstallAzureCLIDeb | sudo bash -
brew update && brew install azure-cli
Imports
- azure.cli.core
from azure.cli.core import get_default_cli
Quickstart
import subprocess
import os
# Ensure Azure CLI is installed and user is logged in (e.g., via `az login` in shell)
# You can also use service principal authentication for CI/CD environments.
def run_az_command(command):
"""Helper to run an az CLI command."""
full_command = ['az'] + command.split()
try:
result = subprocess.run(full_command, capture_output=True, text=True, check=True, env=os.environ)
print(f"Command: {' '.join(full_command)}")
print(f"STDOUT:\n{result.stdout}")
if result.stderr:
print(f"STDERR:\n{result.stderr}")
return result.stdout
except subprocess.CalledProcessError as e:
print(f"Error running command: {' '.join(full_command)}")
print(f"Error STDOUT:\n{e.stdout}")
print(f"Error STDERR:\n{e.stderr}")
raise
# Example 1: List resource groups in JSON format
print("\n--- Listing resource groups ---")
resource_groups_json = run_az_command("group list --output json")
# Further processing with resource_groups_json if needed, e.g., json.loads()
# Example 2: Get current account details
print("\n--- Getting current account details ---")
account_details = run_az_command("account show --output tsv")
# Example 3: Create a resource group (requires appropriate permissions)
# Replace with unique name if running interactively
# RG_NAME = os.environ.get('AZURE_TEST_RG', 'my-python-test-rg')
# LOCATION = os.environ.get('AZURE_TEST_LOCATION', 'eastus')
# print(f"\n--- Creating resource group {RG_NAME} in {LOCATION} ---")
# try:
# run_az_command(f"group create --name {RG_NAME} --location {LOCATION} --output none")
# print(f"Resource group '{RG_NAME}' created successfully.")
# except Exception:
# print(f"Could not create resource group '{RG_NAME}'. It might already exist or permissions are insufficient.")
# Example 4: Delete a resource group (USE WITH CAUTION!)
# print(f"\n--- Deleting resource group {RG_NAME} ---")
# run_az_command(f"group delete --name {RG_NAME} --no-wait --yes")
# print(f"Deletion command issued for resource group '{RG_NAME}'.")