Azure CLI Python Interface

0.5 · active · verified Mon Apr 13

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

Install

Imports

Quickstart

This quickstart demonstrates how to import and use the `az` function to execute an Azure CLI command. It's critical to check the `exit_code` for command success and to understand that `result_dict` only contains parsed JSON output. For other formats or errors, the raw output is in `logs`. Ensure your Azure CLI is installed and you are logged in for commands like `group list` to work.

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

view raw JSON →