Azure CLI Python Interface
az.cli provides a simple Python interface to execute Azure CLI commands directly from Python scripts. It leverages the subprocess module to call the `az` executable installed on the system, passing commands as strings and returning exit codes, parsed JSON results, and raw logs. The current version is 0.5, with releases occurring infrequently as new features or critical bug fixes are implemented.
Warnings
- gotcha The `az.cli` Python library is merely a wrapper. It does NOT bundle the Azure CLI executable. You MUST have the Azure CLI installed and authenticated on the host system where your Python script runs for `az.cli` to function correctly.
- gotcha Error handling for Azure CLI commands through `az.cli` relies on checking the `exit_code` and `logs` returned by the `az()` function. Failures in the underlying CLI command do not raise Python exceptions directly but are indicated by a non-zero `exit_code` and detailed messages in `logs`.
- gotcha The `result_dict` returned by `az()` is populated only when the underlying Azure CLI command successfully outputs valid JSON. For commands that produce other output formats (e.g., `--output tsv`, `--output table`) or on command failure, `result_dict` will be empty or `None`. In such cases, the raw output will be available in the `logs` string.
- deprecated Starting with version 0.4, the `requirements.txt` file was removed to promote a 'loosely coupled' approach. This means the library no longer declares or enforces its direct Python package dependencies (e.g., for JSON parsing).
Install
-
pip install az.cli==0.5
Imports
- az
from az.cli import az
Quickstart
from az.cli import az
# Execute an Azure CLI command
# For example, to list resource groups. Make sure you are authenticated with Azure CLI (e.g., 'az login').
exit_code, result_dict, logs = az("group list")
if exit_code == 0:
print("Azure CLI command executed successfully!")
print("Parsed Result (if JSON output):", result_dict)
if result_dict and isinstance(result_dict, list) and len(result_dict) > 0:
print(f"First resource group name: {result_dict[0].get('name', 'N/A')}")
else:
print(f"Azure CLI command failed with exit code: {exit_code}")
print("Error logs:", logs)
# Example of a command that might not return JSON or returns raw string output
# exit_code, result_dict, logs = az("account show --output tsv")
# if exit_code == 0:
# print("TSV Output (result_dict will be empty for non-JSON):")
# print(logs) # Raw output will be in 'logs' string