Introducing a new way to review your PRs.

Read the announcement

azure / azure-cli

Azure Command-Line Interface

View on GitHub

13 documents · Updated Nov 16, 2026

docs / core-aaz-command-framework

Core AAZ Command Framework

Overview

AAZ (Atomic Azure CLI) is the generated-command framework exported from src/…/__init__.py. Generated command modules import this package to define command/group classes, argument schemas, typed request/response values, HTTP operations, LRO/paging helpers, and Track 2-style clients. The public surface is intentionally aggregated in __init__.py, so changes to framework classes there affect generated command code even when the implementation lives in underscored modules.

Execution starts with generated subclasses of AAZCommand or AAZWaitCommand from src/…/_command.py. register_command and register_command_group decorate those generated classes, derive help text from class docstrings, attach preview/experimental/deprecation metadata, and make them discoverable by AAZ package loaders. load_aaz_command_table performs profile-aware loading using get_aaz_profile_module_name from src/…/utils.py; load_aaz_command_table_args_guided is the optimized route that imports only the generated subtree implied by CLI args unless AZURE_AAZ_FULL_LOAD=true. Both loaders select the active cloud profile package, then populate the Azure CLI loader's command_table and command_group_table with concrete AAZCommand/AAZCommandGroup instances.

When core invokes an AAZ command, AAZCommand._handler in src/…/_command.py builds an AAZCommandCtx from src/…/_command_ctx.py. The context owns formatted args, per-command scratch variables, selectors, cached AAZ clients, the active subscription, auxiliary subscription/tenant sets, no-wait state, and paging next-link state. AAZCommandCtx.format_args() applies schema formatting and converts AAZ validation errors into Azure CLI argument errors. AAZCommandCtx.get_http_client() creates registered AAZ clients with Track 2 client kwargs and appends (AAZ) to the user agent.

Arguments are schema-first. Generated commands override _build_arguments_schema() to return an AAZArgumentsSchema from src/…/_arg.py; the base command appends common --no-wait, generic update, and pagination args when AZ_SUPPORT_NO_WAIT, AZ_SUPPORT_GENERIC_UPDATE, or AZ_SUPPORT_PAGINATION are set. Each AAZBaseArg converts itself to a knack.arguments.CLICommandArgument, including help, configured defaults, local context support, completion, preview/experimental markers, and an argparse action. The actions in src/…/_arg_action.py parse simple values, compound shorthand, JSON/YAML files, blank prompt sentinels, singular list flags, and generic update operations into AAZArgActionOperations; the operations are applied to the typed patch object in AAZCommandCtx after argparse parsing.

Typed values use two parallel layers. src/…/_field_type.py defines schema types such as AAZObjectType, AAZDictType, AAZListType, and simple scalar types; src/…/_field_value.py defines runtime values such as AAZObject, AAZDict, and AAZList. AAZUndefined and AAZValuePatch in src/…/_base.py distinguish omitted data from explicit None and support partial object/list/dict updates. Serialization walks the schema, applies serialized_name, discriminator schemas, client_flatten, read_only, and secret flags, and drops undefined values. AAZCommand.deserialize_output() in _command.py is the common output path that hides secret fields and flattens client-flattened object properties before data reaches CLI output.

Argument formatting is handled by src/…/_arg_fmt.py. Formatters validate and normalize values after parsing: dates/times/durations, UUIDs, numeric bounds, files, resource IDs, subscription IDs, locations, pagination tokens, and nested object/list/dict constraints. Resource ID and subscription formatters update AAZCommandCtx auxiliary subscriptions so the custom bearer-token policy can emit auxiliary tokens for cross-tenant scenarios. AAZPaginationTokenArgFormat validates that decoded next links are trusted cloud endpoints before they are reused.

Generated operations inherit from AAZHttpOperation or JSON/generic instance update helpers in src/…/_operation.py. HTTP operations expose properties for URL, method, URL/query/header params, content, form content, stream content, and error format. make_request() delegates to the selected client, including special handling for ctx.next_link during paging. Static serializers convert AAZ values into URL/query/header/content payloads and enforce required request content while ignoring read-only fields. AAZGenericInstanceUpdateOperation implements Azure CLI-style --set, --add, and --remove over AAZ values, including client-flatten traversal and indexed/filter list access.

Request transport and authentication are Track 2 pipeline based. src/…/_client.py registers named clients with register_client; AAZMgmtClient is registered as MgmtClient and uses the active cloud resource manager endpoint plus resource_to_scopes. AAZClientConfiguration builds core pipeline policies, including AAZBearerTokenCredentialPolicy from src/…/_http_policy.py, which enforces HTTPS, caches main and auxiliary tokens, and emits x-ms-authorization-auxiliary when the credential supports auxiliary tokens. AAZARMChallengeAuthenticationPolicy extends it for ARM CAE claims challenges.

Long-running and paged responses stay inside the AAZ abstraction. AAZCommand.build_lro_poller() in _command.py wraps generated polling generators in AAZLROPoller from src/…/_poller.py; no-wait advances the generator once and returns None, while normal mode runs polling on a background thread and returns the result through a callback. AAZ clients build polling methods with ARM-specific algorithms for management operations. AAZCommand.build_paging() wraps generated executors in AAZPaged from src/…/_paging.py; pagination may emit a base64 next token containing next_link and offset, and later --next-token input is validated by _arg_fmt.py before reuse.

Selectors and content builders are the bridge for generated custom workflows. src/…/_selector.py lets generated selectors expose required JSON resource selection and surface missing resources as user faults. src/…/_content_builder.py maps parsed args into request body values, lazily creates schema properties/elements, supports discriminator-specific builders, and uses src/…/_arg_browser.py to inspect full vs patch argument data. src/…/utils.py provides compatibility helpers for assigning list/dict args while preserving patch semantics.

Developer-facing guidance under this doc's coverage is adjacent rather than part of runtime execution. doc/track_2_migration_guidance.md and doc/track_2_migration_roadmap.md explain why Track 2 SDK migration matters, including LRO naming, property/model/error changes, subscription lookup, and auxiliary authorization. doc/ai_custom_code.md points contributors to the custom-code agent workflow for AAZ subclass customizations and larger OpenSpec-backed changes. These docs should be kept consistent with AAZ runtime behavior in src/azure-cli-core/azure/cli/core/aaz/** when changing generated command customization or Track 2 auth/client expectations.

Routing/coverage note: this document owns src/azure-cli-core/azure/cli/core/aaz/**, doc/ai_custom_code.md, doc/track_2_migration_guidance.md, and doc/track_2_migration_roadmap.md. Use it for reviews that change AAZ command registration/loading, argument parsing/formatting, typed AAZ values, generated request construction, AAZ clients/auth policies, LRO/paging behavior, or the covered contributor guidance. Module-specific generated command packages are outside this doc unless the issue is caused by one of these framework contracts.

Coupling

  • If generated AAZ package __init__.py files start importing command modules eagerly, also revisit load_aaz_command_table_args_guided() in src/…/_command.py; its optimized import path assumes generated package initializers are empty enough that navigating by CLI args does not import the whole command tree.
  • If a new generated client type is introduced, register it with register_client() in src/…/_client.py before generated AAZHttpOperation.CLIENT_TYPE values can use it; AAZCommandCtx.get_http_client() indexes registered_clients directly and will fail loudly for missing keys.
  • If resource ID, subscription, or cross-tenant formatting changes in src/…/_arg_fmt.py, verify AAZCommandCtx.get_login_credential() in src/…/_command_ctx.py and AAZBearerTokenCredentialPolicy in src/…/_http_policy.py; auxiliary subscription/tenant sets are collected during formatting and later become auxiliary authorization headers.
  • If AAZUndefined, patch behavior, or value serialization changes in src/…/_base.py or src/…/_field_value.py, verify request serialization in src/…/_operation.py, content mapping in src/…/_content_builder.py, and generic update behavior in _operation.py; all three rely on undefined-vs-null and patch-vs-full assignment semantics.
  • If shorthand parsing or argument actions change in src/…/_utils.py or src/…/_arg_action.py, verify compound argument help in src/…/_help.py; the ?? help sentinel is thrown from parsing and rendered by the argparse action path.
  • If paging token shape or next-link handling changes in src/…/_paging.py, also update validation in src/…/_arg_fmt.py; AAZPaged expects decoded tokens with next_link and offset, while AAZPaginationTokenArgFormat enforces endpoint trust before AAZHttpOperation.make_request() reuses the link.
  • If the Track 2 client pipeline changes in src/…/_client.py or src/…/_http_policy.py, check doc/track_2_migration_guidance.md; that guidance calls out Track 2 subscription lookup and missing auxiliary authorization support, which AAZ partly solves through its context and bearer-token policy.
  • If output flattening, secret hiding, or schema flags change in src/…/_command.py, src/…/_field_type.py, or src/…/_operation.py, verify generated command expectations: request serialization ignores read_only, response serialization hides secret, and generic update/path lookup uses client_flatten.

Risks

  • src/…/_arg_fmt.py and src/…/_paging.py are security-sensitive around pagination tokens. Recent history includes endpoint-origin hardening (398476be3 {Core} Validate endpoint origin to prevent access token leakage) and URL normalization (cadcc1b68 {Core} Add url normalization in client-side pagination); if validation is weakened, a crafted --next-token could send an Azure access token to an attacker-controlled next-link host.
  • src/…/_poller.py is fragile because LRO polling runs on a background thread. Recent history includes _DeadlockError mitigation (3efe60f58 {Core} Fix #33996: Intermittent _DeadlockError in AAZ long-running operation) and a related import adjustment (463730a67 {Core} aaz: Remove requests in main thread); moving credential creation/import behavior between main and polling threads can reintroduce intermittent Python/MSAL deadlocks.
  • src/…/_field_value.py has special managed-identity serialization. Recent history includes identity preservation fixes (1f3236ec4 [Core] Preserve identities when single instance is removed and df4d0f9e0 chore: limit empty identity to remove); if _build_identity() mishandles empty user-assigned identity sets or system-assigned state, update commands can unintentionally drop identities.
  • src/…/_command.py contains two AAZ command-tree loaders with different assumptions. The args-guided loader was introduced for help/startup performance (e2f8fbf20 {Monitor} ... Args-guided AAZ command tree loading for monitor module); changing generated package layout or fallback loading without testing help paths can hide subcommands from parser/help output or import far more of the command tree than intended.