Azure CLI

2.85.0 · active · verified Thu Apr 09

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

Install

Imports

Quickstart

This quickstart demonstrates how to execute Azure CLI commands programmatically from Python using the `subprocess` module. Users must have the Azure CLI installed and authenticated (e.g., via `az login`) prior to running these commands. This approach is suitable for scripting automation or integrating CLI operations within Python applications.

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}'.")

view raw JSON →