Try Live
Add Docs
Rankings
Pricing
Docs
Install
Install
Docs
Pricing
More...
More...
Try Live
Rankings
Enterprise
Create API Key
Add Docs
Azure Command-Line Interface
https://github.com/azure/azure-cli
Admin
The Azure CLI is a multi-platform command-line experience for managing Azure resources, offering
...
Tokens:
158,804
Snippets:
910
Trust Score:
9.6
Update:
5 months ago
Context
Skills
Chat
Benchmark
51.8
Suggestions
Latest
Show doc for...
Code
Info
Show Results
Context Summary (auto-generated)
Raw
Copy
Link
# Azure CLI ## Introduction The Microsoft Azure CLI (Command-Line Interface) is a cross-platform command-line tool designed for managing Azure resources. Built on Python, it provides a unified interface for developers and administrators to interact with Azure services through commands organized in a hierarchical structure. The CLI supports multiple output formats (JSON, table, TSV), query filtering with JMESPath, tab completion, and extensive telemetry for monitoring usage patterns. With over 100 command modules covering services from virtual machines to Kubernetes, the Azure CLI enables automation, scripting, and interactive management of cloud infrastructure. The Azure CLI architecture follows a modular design where command modules are dynamically loaded based on the command being executed. The core framework is built on the Knack library and provides infrastructure for command registration, argument parsing, authentication, API version management across different cloud profiles, and output formatting. Extensions can be installed to add additional commands without modifying the core CLI installation. The tool supports local context persistence for parameter values, automatic version upgrades, and integration with Azure Cloud Shell for immediate browser-based access without local installation. ## API Documentation ### az CLI Command Execution Execute Azure CLI commands from the command line to manage Azure resources across all supported services. ```bash # Login to Azure az login # Create a resource group az group create --name MyResourceGroup --location eastus # List all resource groups in table format az group list --output table # Create a virtual machine az vm create \ --resource-group MyResourceGroup \ --name MyVM \ --image Ubuntu2204 \ --admin-username azureuser \ --generate-ssh-keys \ --size Standard_B1s # Query specific fields using JMESPath az vm list --query "[?provisioningState=='Succeeded'].{name:name, os:storageProfile.osDisk.osType}" --output table # Show help for any command az storage blob --help # Expected output: Command executes and returns JSON by default # Exit codes: 0=success, 1=generic error, 2=parser error, 3=missing resource ``` ### AzCommandsLoader - Command Module Definition Define custom command modules by inheriting from AzCommandsLoader to register commands and arguments. ```python # __init__.py in azure/cli/command_modules/mymod/ from azure.cli.core import AzCommandsLoader from azure.cli.core.commands import CliCommandType from azure.cli.command_modules.mymod._help import helps class MyModCommandsLoader(AzCommandsLoader): def __init__(self, cli_ctx=None): super().__init__(cli_ctx=cli_ctx, min_profile='2017-03-09-profile') def load_command_table(self, args): # Define command type with operations template mymod_custom = CliCommandType( operations_tmpl='azure.cli.command_modules.mymod.custom#{}', ) mymod_sdk = CliCommandType( operations_tmpl='azure.mgmt.myservice.operations#MyServiceOperations.{}', client_factory=cf_myservice ) # Register command groups and commands with self.command_group('myservice', mymod_sdk) as g: g.command('create', 'begin_create_or_update') g.command('delete', 'begin_delete') g.show_command('show', 'get') g.command('list', 'list_by_subscription') with self.command_group('myservice item', mymod_custom) as g: g.custom_command('add', 'add_item') g.custom_command('remove', 'remove_item') return self.command_table def load_arguments(self, command): from azure.cli.core.commands.parameters import tags_type, get_enum_type with self.argument_context('myservice') as c: c.argument('name', options_list=['--name', '-n'], help='Name of the service') c.argument('resource_group_name', options_list=['--resource-group', '-g']) c.argument('tags', tags_type) c.argument('sku', arg_type=get_enum_type(['Basic', 'Standard', 'Premium'])) COMMAND_LOADER_CLS = MyModCommandsLoader # Expected: Commands registered and available via 'az myservice create', 'az myservice item add' ``` ### Custom Command Implementation Implement command handlers as Python functions with type-annotated parameters for automatic argument parsing. ```python # custom.py in azure/cli/command_modules/mymod/ from azure.cli.core.util import sdk_no_wait def create_myservice(cmd, resource_group_name, name, location, sku='Standard', tags=None, no_wait=False): """ Create a new instance of MyService. :param cmd: Command context with CLI context :param resource_group_name: Name of resource group :param name: Name of the service instance :param location: Azure region :param sku: Service tier :param tags: Resource tags :param no_wait: Do not wait for operation to complete """ from azure.mgmt.myservice.models import MyServiceResource, Sku from azure.cli.command_modules.mymod._client_factory import cf_myservice client = cf_myservice(cmd.cli_ctx) # Construct the service resource service_resource = MyServiceResource( location=location, sku=Sku(name=sku), tags=tags or {} ) # Execute the creation operation return sdk_no_wait(no_wait, client.begin_create_or_update, resource_group_name, name, service_resource) def add_item(cmd, resource_group_name, service_name, item_name, item_value): """Add an item to the service configuration.""" from azure.cli.command_modules.mymod._client_factory import cf_myservice client = cf_myservice(cmd.cli_ctx) service = client.get(resource_group_name, service_name) # Modify the service configuration if not service.items: service.items = [] service.items.append({'name': item_name, 'value': item_value}) # Update and return return client.begin_create_or_update(resource_group_name, service_name, service) # Expected: Functions callable via CLI with automatic parameter mapping # Usage: az myservice create -g MyRG -n MyService -l eastus --sku Premium --tags env=prod ``` ### Client Factory Pattern Define client factories to instantiate Azure SDK clients with proper authentication and configuration. ```python # _client_factory.py in azure/cli/command_modules/mymod/ def get_myservice_management_client(cli_ctx, **kwargs): """Get the MyService management client with proper credentials.""" from azure.cli.core.commands.client_factory import get_mgmt_service_client from azure.mgmt.myservice import MyServiceManagementClient return get_mgmt_service_client( cli_ctx, MyServiceManagementClient, subscription_id=kwargs.get('subscription_id') ) def cf_myservice(cli_ctx, *_): """Factory for MyService operations client.""" return get_myservice_management_client(cli_ctx).my_services def cf_myservice_items(cli_ctx, *_): """Factory for MyService items operations client.""" return get_myservice_management_client(cli_ctx).items # Usage in command registration: # mymod_sdk = CliCommandType( # operations_tmpl='azure.mgmt.myservice.operations#MyServicesOperations.{}', # client_factory=cf_myservice # ) # Expected: Clients automatically configured with correct credentials and subscription ``` ### Argument Context and Parameter Configuration Configure command arguments with validation, completion, and transformation options. ```python # _params.py in azure/cli/command_modules/mymod/ from azure.cli.core.commands.parameters import ( get_resource_name_completion_list, tags_type, get_enum_type, get_three_state_flag ) from azure.cli.core.commands.validators import get_default_location_from_resource_group def load_arguments(self, _): with self.argument_context('myservice') as c: c.argument('resource_group_name', options_list=['--resource-group', '-g'], completer=get_resource_name_completion_list('Microsoft.Resources/resourceGroups'), help='Name of resource group') c.argument('name', options_list=['--name', '-n'], completer=get_resource_name_completion_list('Microsoft.MyService/services'), help='Name of the MyService instance') c.argument('location', validator=get_default_location_from_resource_group, help='Location. Values from: az account list-locations') c.argument('tags', tags_type) c.argument('sku', arg_type=get_enum_type(['Basic', 'Standard', 'Premium']), help='Pricing tier') with self.argument_context('myservice create') as c: c.argument('enable_feature', arg_type=get_three_state_flag(), help='Enable the advanced feature') c.argument('connection_string', options_list=['--connection-string'], validator=validate_connection_string, help='Connection string for external service') def validate_connection_string(namespace): """Custom validator for connection strings.""" if namespace.connection_string: if not namespace.connection_string.startswith('Endpoint='): raise ValueError('Connection string must start with "Endpoint="') # Expected: Arguments have tab completion, validation, and proper help text ``` ### AzCli Core Initialization Initialize the Azure CLI with configuration, authentication, and cloud profile settings. ```python # Core CLI initialization (from azure.cli.core) from azure.cli.core import get_default_cli from azure.cli.core.cloud import get_active_cloud # Get the default CLI instance az_cli = get_default_cli() # Access CLI configuration config_dir = az_cli.config.config_dir # ~/.azure collect_telemetry = az_cli.config.getboolean('core', 'collect_telemetry', fallback=True) output_format = az_cli.config.get('core', 'output', fallback='json') # Get active cloud configuration cloud = get_active_cloud(az_cli) print(f"Active cloud: {cloud.name}") print(f"ARM endpoint: {cloud.endpoints.resource_manager}") print(f"Storage endpoint: {cloud.suffixes.storage_endpoint}") # Invoke a command programmatically exit_code = az_cli.invoke(['group', 'list', '--output', 'json']) # Handle custom command execution def cli_main(cli, args): """Main CLI entry point.""" return cli.invoke(args) # Execute with arguments import sys exit_code = cli_main(az_cli, sys.argv[1:]) sys.exit(exit_code) # Expected: CLI initialized with proper config, cloud endpoints, and ready for command execution ``` ### Command Table and Dynamic Loading Register commands with dynamic module loading based on command index for performance optimization. ```python # Command loader implementation (from MainCommandsLoader) from azure.cli.core import MainCommandsLoader class CustomCommandsLoader(MainCommandsLoader): def load_command_table(self, args): """Load command modules dynamically based on command index.""" # Command index maps top-level commands to modules # Example: 'vm' -> ['azure.cli.command_modules.vm'] command_index = self.cli_ctx.invocation.data.get('command_index', {}) # Load only required modules for the command if args and not args[0].startswith('-'): top_command = args[0] modules = command_index.get(top_command, []) for mod in modules: self._load_module(mod, args) else: # Load all modules if no command specified self._load_all_modules(args) return self.command_table def _load_module(self, module_name, args): """Load a specific command module.""" from importlib import import_module mod = import_module(f'azure.cli.command_modules.{module_name}') loader_cls = getattr(mod, 'COMMAND_LOADER_CLS') loader = loader_cls(cli_ctx=self.cli_ctx) # Load commands from the module module_commands = loader.load_command_table(args) self.command_table.update(module_commands) # Track loaders for argument loading for cmd_name in module_commands: if cmd_name not in self.cmd_to_loader_map: self.cmd_to_loader_map[cmd_name] = [] self.cmd_to_loader_map[cmd_name].append(loader) # Usage: Commands loaded on-demand, improving startup performance # 'az vm create' only loads VM module, not storage/network modules ``` ### Extension Management Install and manage CLI extensions to add functionality without modifying core installation. ```bash # List available extensions az extension list-available --output table # Install an extension az extension add --name azure-devops # Update an extension az extension update --name azure-devops # List installed extensions az extension list --output table # Remove an extension az extension remove --name azure-devops # Install extension from local path or URL az extension add --source ~/extensions/my_extension-1.0.0-py3-none-any.whl # Install extension from index URL az extension add --name my-extension --source https://example.com/extensions # Expected output: Extension installed and commands immediately available # Extension commands: az devops project create, az devops pipeline run, etc. ``` ### Query Output with JMESPath Filter and transform command output using JMESPath query syntax for precise data extraction. ```bash # Query for specific fields az vm list --query "[].{name:name, size:hardwareProfile.vmSize}" --output table # Filter with conditions az vm list --query "[?provisioningState=='Succeeded']" --output json # Get first item from array az vm list --query "[0].name" --output tsv # Complex nested query az vm show --resource-group MyRG --name MyVM \ --query "{name:name, os:storageProfile.osDisk.osType, privateIP:networkProfile.networkInterfaces[0].ipConfigurations[0].privateIpAddress}" # Query with functions az group list --query "sort_by([].{name:name, location:location}, &location)" --output table # Multiple fields with renaming az resource list --query "[?type=='Microsoft.Compute/virtualMachines'].{VM_Name:name, ResourceGroup:resourceGroup, Location:location}" --output table # Expected: Filtered JSON/table output with only requested fields # Example output: # VM_Name ResourceGroup Location # --------- --------------- ---------- # MyVM MyRG eastus # TestVM TestRG westus ``` ### Configuration Management Manage CLI configuration settings including defaults, output format, and parameter persistence. ```bash # Set default output format az config set core.output=table # Set default location az config set defaults.location=eastus # Set default resource group az config set defaults.group=MyResourceGroup # Enable/disable telemetry collection az config set core.collect_telemetry=false # Configure parameter persistence az config param-persist on # Show all configuration values az config get # Unset a configuration value az config unset defaults.location # Expected: Configuration saved to ~/.azure/config # Commands use configured defaults automatically # Example: 'az group create --name NewRG' uses default location ``` ### REST API Direct Access Execute arbitrary REST API calls against Azure Resource Manager endpoints without specific command support. ```bash # Generic GET request az rest --method GET --url https://management.azure.com/subscriptions/{subscriptionId}/resourceGroups?api-version=2021-04-01 # POST request with body az rest --method POST \ --url https://management.azure.com/subscriptions/{subscriptionId}/resourceGroups/MyRG/providers/Microsoft.Compute/virtualMachines/MyVM/start?api-version=2023-03-01 \ --body '{}' # PUT request with JSON body from file az rest --method PUT \ --url https://management.azure.com/subscriptions/{subscriptionId}/resourceGroups/MyRG/providers/Microsoft.Storage/storageAccounts/mystore?api-version=2023-01-01 \ --body @storage-account.json # DELETE request az rest --method DELETE \ --url https://management.azure.com/subscriptions/{subscriptionId}/resourceGroups/MyRG/providers/Microsoft.Network/publicIPAddresses/MyIP?api-version=2023-05-01 # Add custom headers az rest --method GET \ --url https://graph.microsoft.com/v1.0/me \ --headers "ConsistencyLevel=eventual" # Expected: Raw REST API response in JSON format # Useful for preview features or APIs without CLI command support ``` ### Breaking Change Detection Declare and track breaking changes in commands using decorators and metadata for user warnings. ```python # Declare breaking changes in command modules from azure.cli.core.breaking_change import register_breaking_change # In module initialization def load_command_table(self, args): with self.command_group('myservice') as g: g.command('create', 'create_myservice', deprecate_info=self.deprecate( redirect='myservice create-v2', hide=False, expiration='2.50.0' )) # Using decorator for breaking changes @register_breaking_change( version='2.45.0', message='--legacy-param will be replaced with --new-param', action='parameter' ) def create_myservice(cmd, resource_group_name, name, legacy_param=None, new_param=None): if legacy_param: from azure.cli.core.azclierror import ArgumentUsageError logger.warning("Parameter --legacy-param is deprecated. Use --new-param instead.") # Implementation pass # Breaking change info structure breaking_change_info = { 'version': '2.45.0', 'target': 'az myservice create', 'type': 'parameter', 'message': '--legacy-param will be replaced with --new-param', 'link': 'https://aka.ms/azcli/breaking-changes' } # Expected: Users see warnings when using deprecated commands/parameters # Warning: This command has been deprecated and will be removed in version 2.50.0. # Use 'myservice create-v2' instead. ``` ### Local Context and Parameter Persistence Enable parameter persistence to save frequently used argument values across command invocations. ```bash # Enable parameter persistence az config param-persist on # Set values that will be persisted az group create --name MyResourceGroup --location eastus # Values saved: resource_group_name=MyResourceGroup, location=eastus # Subsequent commands use persisted values automatically az storage account create --name mystorageacct --sku Standard_LRS # Automatically uses: --resource-group MyResourceGroup --location eastus # Show persisted parameters az config param-persist show # Clear specific parameter az config param-persist delete --name location # Clear all persisted parameters az config param-persist off # Disable parameter persistence az config param-persist off # Expected: Common parameters saved in .azure/param-persist.json # Reduces repetitive typing for resource group, location, etc. ``` ### Telemetry and Usage Tracking CLI automatically collects usage telemetry while respecting privacy settings and user preferences. ```python # Telemetry implementation (azure.cli.core.telemetry) from azure.cli.core import telemetry # Mark command execution as successful telemetry.set_success() # Track custom events telemetry.add_extension_event('extension_name', {'action': 'install', 'version': '1.0.0'}) # Log exceptions with fault type try: # Command execution pass except Exception as ex: telemetry.set_exception( exception=ex, fault_type='command-execution-error', summary='Failed to execute command' ) # Record performance metrics telemetry.set_init_time_elapsed("0.523") telemetry.set_invoke_time_elapsed("2.145") # User opt-out # CLI respects: az config set core.collect_telemetry=no # Telemetry data includes: # - Command name and parameters (scrubbed of sensitive data) # - Execution time and result (success/failure) # - Python version, OS, CLI version # - Extension usage # - Error types (no stack traces with personal data) # Expected: Anonymous usage data sent to Microsoft for product improvement # All PII automatically masked by microsoft-security-utilities-secret-masker ``` ## Summary The Azure CLI serves as the primary command-line interface for managing Azure cloud resources, offering comprehensive coverage of Azure services through a modular, extensible architecture. Its core use cases include infrastructure provisioning and management, automation through scripts and CI/CD pipelines, interactive resource exploration and troubleshooting, and cross-platform cloud administration. The tool excels in scenarios requiring batch operations, declarative infrastructure configuration, and integration with version control systems for infrastructure-as-code workflows. With support for multiple authentication methods including service principals, managed identities, and device code flow, the CLI adapts to various deployment contexts from developer workstations to automated build agents. Integration patterns for the Azure CLI span multiple domains: embedding in shell scripts for automation, integration with container-based workflows through official Docker images, extension through the Python-based command module architecture, and programmatic invocation from Python applications using the core libraries. The CLI's design emphasizes backward compatibility through API versioning, cloud profile support for different Azure environments (public, government, China), and automatic command indexing for fast startup times. Local context persistence and argument defaults reduce verbosity in interactive sessions, while JMESPath query support enables sophisticated output filtering and transformation directly in the command line without external tools like jq or awk.