Core Extension Management
Overview
This area covers Azure CLI's extension framework and the built-in az extension command surface. Route here for changes under src/azure-cli-core/azure/cli/core/extension/**, src/azure-cli/azure/cli/command_modules/extension/**, and doc/extensions/**, plus direct integration points that load extension command tables or trigger dynamic installation.
Extension discovery is centered in src/…/__init__.py. User-installed wheel extensions live under EXTENSIONS_DIR, defaulting to <global config>/cliextensions; system extensions live under EXTENSIONS_SYS_DIR, defaulting to azure-cli-extensions under the running Python purelib; development extensions are discovered by recursively scanning configured extension.dev_sources. WheelExtension.get_all() and DevExtension.get_all() return sorted Extension objects so override behavior is deterministic, and get_extension_modname() enforces that an installed extension directory contains exactly one azext_* package. Metadata is lazy-loaded from package *.dist-info/*.egg-info plus optional azext_*/azext_metadata.json; compatibility and preview/stable classification use azext.minCliCoreVersion, azext.maxCliCoreVersion, azext.isPreview, azext.isExperimental, and semantic prerelease markers in the same file.
Extension command loading happens when the main command table is built, not in the az extension command module itself. src/…/__init__.py calls get_extensions(), filters by requested extension module names from the command index when available, checks compatibility through check_version_compatibility(), appends the extension directory to sys.path, resolves the azext_* package, and delegates to _load_extension_command_loader() in src/…/__init__.py. Each loaded command is marked with ExtensionCommandSource, which records the extension name, whether it overrides a built-in command, and preview/experimental status for parser/help warnings. CommandIndex.update_extension_index() in src/…/__init__.py maintains the latest-profile extension overlay index; CommandIndex.invalidate() is called after add/update/remove so new extension commands and overrides are not hidden by stale indexing.
Installation and lifecycle flows are implemented in src/…/operations.py and exposed through thin wrappers in src/…/custom.py. add_extension() either resolves a named extension from the index or installs a local/remote wheel supplied by --source; _add_whl_ext() validates the wheel filename, downloads remote wheels, verifies an optional SHA-256 digest, extracts the wheel long enough to read azext_metadata.json, checks CLI compatibility, runs pip with --target into the extension directory, and copies the wheel artifact into that directory. Updates use resolve_from_index() with the current version threshold, back up the existing extension directory, remove it, install the replacement, and restore the backup if installation fails. Removal refuses dev extensions and Cloud Shell system extensions, then deletes the installed directory. Listing/showing installed extensions uses the lazy metadata and path data from Extension objects; listing available versions reads the index and filters by CLI compatibility.
Index handling is split between src/…/_index.py and _resolve.py. _index.get_index_url() chooses extension.index_url from CLI config, an azmirror_storage_account_resource_id cloud endpoint, or https://aka.ms/azure-cli-extension-index-v1; _index.get_index() retries HTTP retrieval three times and expects an extensions object. _resolve.resolve_from_index() filters candidates by universal wheel tag, stable/preview policy, requested version or newer-than-current version, and CLI compatibility, then returns (downloadUrl, sha256Digest). For air-gapped mirrored clouds it rewrites the wheel URL to the mirror endpoint when no explicit config index URL is set.
Dynamic installation is in src/…/dynamic_install.py and is invoked from parser choice errors in src/…/parser.py. The dynamic flow loads a cached extensionCommandTree.json from the CLI config directory or downloads it from https://aka.ms/azExtCmdTree/the cloud mirror, treats it as a prefix tree from command words to extension names, and only attempts installation when the unknown command path maps to an extension. Configuration under the extension section controls whether dynamic install is disabled, prompted, or automatic; whether the command is rerun after install; and whether preview extension versions are eligible. When rerun is enabled, the code calls run_az_cmd(args[1:]) in-process rather than handing user arguments to a shell.
The built-in command surface is registered by src/…/__init__.py. It defines az extension add/remove/list/show/list-available/update/list-versions, validates that add receives exactly one of --name or --source, wires --allow-preview as a three-state flag, exposes pip proxy/index options, and hides --index. Completion in _completers.py reads installed extension names from get_extension_names() and available names from the remote index. User help lives in _help.py.
Author-facing guidance under doc/extensions/** documents the contract that the runtime enforces: extensions are Python wheels (doc/…/README.md), optional azext_metadata.json fields are described in doc/…/metadata.md, development/publishing flows and dependency constraints are in doc/…/authoring.md, and preview/stable version semantics and --allow-preview behavior are in doc/…/versioning_guidelines.md.
Coupling
- If src/…/__init__.py changes extension metadata keys, preview detection, or azext_metadata.json loading, also update doc/…/metadata.md and doc/…/versioning_guidelines.md; install-time compatibility in operations.py, candidate filtering in _resolve.py, and list output all consume the same metadata dictionary.
- If
_resolve.resolve_from_index()changes the accepted index schema, also update_index.get_index_extensions(),operations.list_available_extensions(),operations.list_versions(), and_completers.extension_name_from_index_completion_list(); these paths assume the index maps extension names to candidate dictionaries withfilename,downloadUrl,sha256Digest, and nestedmetadata.version/metadata.summary. - If add/update/remove flows in src/…/operations.py stop calling
CommandIndex().invalidate(), verify extension overrides and commands under existing built-in groups with src/…/__init__.py; a stale command index can keep the core module route active and ignore a newly installed extension. - If the extension installation path rules change in __init__.py, also verify
operations.add_extension_to_path(), src/…/util.py version output, and src/…/_help.py; users see both the normal and system extension directories and extensions may extend theazure/azure.mgmtnamespace from their install path. - If dynamic install configuration keys or preview defaults change in dynamic_install.py, also update src/…/__init__.py, _help.py, and doc/…/versioning_guidelines.md; manual add/update and dynamic install share the
allow_previewsemantics but obtain the value from different surfaces. - If extension command loading changes in src/…/__init__.py or
_load_extension_command_loader()in src/…/__init__.py, verifyExtensionCommandSourcebehavior in parser/help paths and src/…/client_factory.py; extension custom operations are identified by theazext_module prefix when resolving client argument conventions. - If extensionCommandTree.json generation or schema changes outside this area, update
_search_in_extension_commands()in dynamic_install.py; it expects nested dictionaries where string leaves are extension names and help prefix matches may return multiple candidate extensions.
Risks
- src/…/dynamic_install.py reruns user commands after installing an extension. Commit history includes
97ee957c4 {Core} Fix injection risk during extension dynamic installation (#33990), and the current code intentionally usesrun_az_cmd(args[1:])instead of shelling out; reverting to subprocess/shell execution would let command arguments be reinterpreted by a shell. - src/…/dynamic_install.py can loop or mask parser errors if it treats every parse failure as a missing extension. The guard that checks whether the latest extension is already installed is tied to past churn (
135b525d9 {Core} Hotfix: Fix inifite extension install loop (#17698)); changing_check_value_in_extensions()should preserve the installed-extension/newer-candidate check. - src/…/operations.py update rollback depends on copying the existing extension directory before deletion and restoring it on any install exception. If backup or restore logic changes, a failed
az extension updatecan leave the extension missing; the file has a long history of extension install/update fixes, including retrying removal and improving failure feedback. - src/…/_resolve.py and doc/…/versioning_guidelines.md encode the stable-by-default preview policy introduced by
b1f35f203 [Core] BREAKING CHANGE: az extension add/update and az upgrade: Install stable version for extension by default. If preview filtering orallow_preview is Nonehandling changes without synchronized docs and command help, users may unexpectedly install preview builds or fail to find extensions that only publish preview versions. - src/…/operations.py contains special system dependency installation for
rdbms-connectandserviceconnector-passwordless. It shells out to platform package managers and has history of environment-specific fixes, including Cloud Shell and Docker handling; changes here can break extension installation only on specific distros or installers.