Azure CLI Core Runtime Invocation
Overview
The Azure CLI core runtime is constructed by src/azure-cli-core/azure/cli/core/__init__.py:get_default_cli(), which returns an AzCli instance named az with Azure-specific implementations for command loading, invocation, parsing, logging, output, and help. AzCli.__init__() initializes process-wide runtime state under the CLI config directory from src/…/_config.py and src/…/_environment.py: profile/account data (azureProfile.json), config/session JSON (az.json, az.sess), command/help indexes, extension overlay indexes, and version-check state via the Session objects in src/…/_session.py. It also resolves the active cloud, local parameter context, global transforms, global subscription/--ids/policy/cache arguments, breaking-change messages, and color theme setup.
Runtime invocation is centered on src/azure-cli-core/azure/cli/core/commands/__init__.py:AzCliCommandInvoker.execute(). Before command loading it refreshes x-ms-client-request-id through AzCli.refresh_request_id() and expands @file argument values with _expand_file_prefixed_files(). It then raises command-table lifecycle events, asks MainCommandsLoader.load_command_table() from src/…/__init__.py to load only the relevant command modules/extensions when possible, truncates the table to the likely command prefix, loads command arguments, builds the AzCliCommandParser, and parses arguments. After parsing it records telemetry-safe parameter names, resolves extension metadata, emits preview/deprecation/breaking-change warnings, prompts for destructive confirmations, validates command and argument validators, runs one or more jobs, transforms SDK results to dictionaries, raises result-filter events, warns about secrets, persists local context values, and returns a Knack CommandResultItem for formatting.
Command discovery has two paths in src/azure-cli-core/azure/cli/core/__init__.py:MainCommandsLoader.load_command_table(). The fast path uses CommandIndex caches in commandIndex.json, extensionIndex.json, helpIndex.json, and extensionHelpIndex.json; on the latest profile it can blend packaged commandIndex.latest.json / helpIndex.latest.json with local extension overlays. If the index is absent or stale, the loader discovers azure.cli.command_modules, imports each module command loader through src/azure-cli-core/azure/cli/core/commands/__init__.py:_load_module_command_loader(), imports installed extension loaders through _load_extension_command_loader(), checks extension compatibility, applies extension suppressions from ModExtensionSuppress, and merges command/group tables. CommandIndex.invalidate() must be called by extension install/update/removal flows because stale indexes can hide extension overrides or extension-provided subgroups.
Command authoring support lives in src/azure-cli-core/azure/cli/core/__init__.py:AzCommandsLoader, src/azure-cli-core/azure/cli/core/commands/__init__.py:AzCommandGroup, and src/…/command_operation.py. Command groups resolve operations_tmpl strings to operation paths and wrap them in CommandOperation, ShowCommandOperation, GenericUpdateCommandOperation, or WaitCommandOperation. These operation classes import the target operation lazily, patch unversioned SDK paths through src/azure-cli-core/azure/cli/core/profiles/_shared.py:get_versioned_sdk_path(), reflect handler signatures into CLI arguments, inject clients from command kwargs, handle --no-wait, and implement generic update/wait behavior. src/azure-cli-core/azure/cli/core/commands/parameters.py:AzArgumentContext applies argument overrides only when the active cloud profile supports the requested resource/API version and wires common globals like resource group, location, deployment name, VNet/subnet, tags, and --no-wait.
Argument parsing is implemented by src/azure-cli-core/azure/cli/core/parser.py:AzCliCommandParser. It constructs subparsers from the loaded command table, attaches command/argument validators, tracks explicitly specified argument destinations for local-context persistence, enables case-insensitive shell completion through AzCompletionFinder, and maps parse failures to Azure CLI error classes such as CommandNotFoundError, UnrecognizedArgumentError, RequiredArgumentMissingError, and InvalidArgumentValueError. Parser failures also feed src/…/command_recommender.py for command/example recommendations and set telemetry-safe command details for help requests.
Execution results are normalized in AzCliCommandInvoker._run_job() in src/…/__init__.py: command handlers return SDK objects, pages, or pollers; transforms run first, pollers are handled by LongRunningOperation, paged iterators are materialized, and src/azure-cli-core/azure/cli/core/util.py:todict() converts SDK models, Track 2 models, enums, datetimes, lists, and dictionaries into output-ready Python values. Output format state is stored in cli_ctx.invocation.data['output'] by helpers in src/…/_output.py; AzOutputProducer delegates actual formatting to Knack while adding Azure CLI format validation, and apply_output_newline() can reconfigure stdout newline translation according to core.output_newline and the AZ_LAUNCHER environment signal.
Logging is configured by src/azure-cli-core/azure/cli/core/azlogging.py:AzCliLogging. It extends Knack logging with secure 0600 rotating log files, disables duplicate Track 2 HTTP logging when --debug is active, and creates per-command metadata logs under <config_dir>/commands on CommandInvoker.OnPreCommandTableTruncate. Command metadata logs contain sanitized command arguments from _get_clean_args(), extension name/version when available, and the final exit code on EVENT_CLI_POST_EXECUTE; older per-command logs are pruned to keep recent history only. Errors printed through src/azure-cli-core/azure/cli/core/azclierror.py:AzCLIError.print_error() also duplicate error lines into the metadata logger through CommandLoggerContext so az feedback has the failure context.
Error mapping is split between src/…/azclierror.py and src/azure-cli-core/azure/cli/core/util.py:handle_exception(). Runtime exceptions from SDKs, JMESPath, Knack CLIError, HTTP libraries, Azure Core, msrest, keyboard interrupts, and token-cache persistence are converted into Azure CLI error classes with recommendations and telemetry classification. Resource-not-found errors return exit code 3; most other handled errors return 1; parser errors exit with 2 directly from AzCliCommandParser after printing and sending telemetry.
Profiles and SDK routing are part of runtime command invocation because command registration and operation import depend on the active cloud profile. src/…/__init__.py exposes get_api_version(), supported_api_version(), supported_resource_type(), and get_sdk() over AZURE_API_PROFILES in src/…/_shared.py. AzCommandsLoader.supported_api_version() and AzArgumentContext.argument() use these gates while CommandOperation.get_op_handler() and AzCommandsLoader.get_op_handler() rewrite imports like azure.mgmt.<service> to versioned SDK packages when the profile provides a specific API version.
Routing / coverage note: this document owns the core runtime flow under src/…/*.py, src/azure-cli-core/azure/cli/core/commands/**, src/azure-cli-core/azure/cli/core/profiles/**, plus the empty src/azure-cli-core/setup.cfg and minimal src/azure-cli-core/README.rst. It intentionally stops at command-module and extension boundaries: modules under azure.cli.command_modules, extension management internals, auth package internals, and AAZ implementation details are referenced only where these core runtime files call into them.
Coupling
- If
src/azure-cli-core/azure/cli/core/__init__.py:get_default_cli()changes any runtime class, verifysrc/azure-cli-core/azure/cli/core/commands/__init__.py:AzCliCommandInvoker,src/azure-cli-core/azure/cli/core/parser.py:AzCliCommandParser,src/azure-cli-core/azure/cli/core/azlogging.py:AzCliLogging, andsrc/azure-cli-core/azure/cli/core/_output.py:AzOutputProducerstill satisfy Knack's constructor and event expectations; these classes are coupled by name throughget_default_cli()rather than a local integration layer. - If command index schema or profile/version metadata changes in
src/azure-cli-core/azure/cli/core/__init__.py:CommandIndex, also update the persistedSessionkeys in src/…/_session.py and the packaged latest-profile index readers in the same class.MainCommandsLoader.load_command_table()trusts those keys to decide whether to skip full module loading. - If extension install/update/removal behavior changes outside this doc, verify it still calls
src/azure-cli-core/azure/cli/core/__init__.py:CommandIndex.invalidate(). Without invalidation,MainCommandsLoader.load_command_table()can use stale module/extension mappings and silently ignore extension overrides or extension-expanded command groups. - If new command lifecycle events are added or existing ones are moved in
src/azure-cli-core/azure/cli/core/commands/__init__.py:AzCliCommandInvoker.execute(), check handlers registered in src/…/arm.py, src/…/transform.py, src/…/breaking_change.py, src/…/azlogging.py, andregister_cache_arguments()in src/…/__init__.py; these hooks rely on parse/load ordering to add global args, parse--ids, log metadata, emit breaking-change text, and transform results. - If src/…/parser.py changes parse-error classification or safe-argument extraction, verify
src/azure-cli-core/azure/cli/core/commands/__init__.py:AzCliCommandInvoker._extract_parameter_names()andsrc/azure-cli-core/azure/cli/core/azlogging.py:AzCliLogging._get_clean_args()remain aligned. Telemetry and command metadata logs assume only parameter names/placeholders are recorded, not raw secrets or positional values. - If src/…/_shared.py changes
ResourceType,SDKProfile, orget_versioned_sdk_path(), verify command registration insrc/azure-cli-core/azure/cli/core/__init__.py:AzCommandsLoader, operation import in src/…/command_operation.py, and argument applicability in src/…/parameters.py; all three independently use profile gates and can diverge if SDK routing semantics shift. - If result conversion changes in
src/azure-cli-core/azure/cli/core/util.py:todict()or poller detection insrc/azure-cli-core/azure/cli/core/commands/__init__.py:_is_poller(), verifyLongRunningOperation, command transforms, and output formatting still receive dictionaries/lists rather than SDK model instances. Output-sensitive-data scanning inAzCliCommandInvoker._resolve_output_sensitive_data_warning()also depends on the normalized result shape. - If
core.output_newline,AZ_LAUNCHER, or stdout handling changes in src/…/_output.py, verify the event registration site still invokesapply_output_newline()before command output is written. The helper mutatescli_ctx.out_file/sys.stdoutin place because Knack keeps stream references.
Risks
src/azure-cli-core/azure/cli/core/__init__.py:MainCommandsLoader.load_command_table()andCommandIndexhave multiple fallback branches for packaged latest-profile indexes, local extension overlays, top-level completion stubs, cached top-level help, and full module reload. If a branch returns an incomplete command table for a real invocation, users can seeCommandNotFoundErroreven though a module or extension is installed.src/azure-cli-core/azure/cli/core/commands/__init__.py:AzCliCommandInvoker._run_jobs_concurrently()appends exceptions usingids[index]while iteratingas_completed(tasks). If several--idsjobs run concurrently and one fails, the warning can associate an exception with the wrong original id because completion order is not submission order.src/azure-cli-core/azure/cli/core/commands/__init__.py:LongRunningOperation.__call__()reads private poller response internals (poller._response.__dict__['_content']) to discover ARM deployment correlation IDs. If SDK poller internals change, progress reporting can stop showing correlation/activity updates; the command result still completes unless later code starts depending on that correlation ID.src/azure-cli-core/azure/cli/core/commands/command_operation.py:BaseCommandOperation.get_op_handler()andsrc/azure-cli-core/azure/cli/core/__init__.py:AzCommandsLoader.get_op_handler()duplicate operation import and profile path rewriting logic. A fix applied to only one path can make commands registered throughAzCommandGroupbehave differently from legacy_cli_command()registrations.src/azure-cli-core/azure/cli/core/azlogging.py:AzCliLogging._get_clean_args()andsrc/azure-cli-core/azure/cli/core/commands/__init__.py:AzCliCommandInvoker._extract_parameter_names()both treat tokens beginning with more than two dashes as values to support PEM-like inputs. If option parsing semantics change without updating both helpers, telemetry/log sanitization can either lose useful parameter names or expose raw argument values.