# https://github.com/ansible/ansible 项目说明书

生成时间：2026-07-09 19:53:05 UTC

## 目录

- [项目概览与代码组织](#page-1)
- [Playbook 执行核心](#page-2)
- [模块、插件与连接体系](#page-3)
- [Inventory、Templating 与 CLI 工具链](#page-4)

<a id='page-1'></a>

## 项目概览与代码组织

### 相关页面

相关主题：[Playbook 执行核心](#page-2), [模块、插件与连接体系](#page-3), [Inventory、Templating 与 CLI 工具链](#page-4)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [README.md](https://github.com/ansible/ansible/blob/main/README.md)
- [lib/ansible/release.py](https://github.com/ansible/ansible/blob/main/lib/ansible/release.py)
- [lib/ansible/__init__.py](https://github.com/ansible/ansible/blob/main/lib/ansible/__init__.py)
- [bin/ansible](https://github.com/ansible/ansible/blob/main/bin/ansible)
- [context/README.md](https://github.com/ansible/ansible/blob/main/context/README.md)
- [changelogs/README.md](https://github.com/ansible/ansible/blob/main/changelogs/README.md)
- [lib/ansible/cli/__init__.py](https://github.com/ansible/ansible/blob/main/lib/ansible/cli/__init__.py)
- [lib/ansible/inventory/__init__.py](https://github.com/ansible/ansible/blob/main/lib/ansible/inventory/__init__.py)
</details>

# 项目概览与代码组织

## 项目定位与范围

`ansible/ansible` 仓库托管的是 **Ansible Core**（即 `ansible-core`），它是 Ansible 生态中负责运行时、连接层、内置模块与 CLI 框架的核心代码库。与位于 `ansible-collections` 组织的社区集合配合，`ansible-core` 提供"引擎 + 内置"，集合提供"领域模块"，共同构成完整的 Ansible 自动化体验。

仓库自述文件说明本项目以 Python 编写，目标运行时为 CPython 3.11+，同时为支持 Windows 节点保留了 PowerShell 模块实现。Ansible Core 与 Ansible Community 在治理上是分开的：核心遵循自身的发版节奏，社区集合则独立发版并通过 `ansible-galaxy collection install` 加载。 资料来源：[README.md:1-40]()

## 代码组织总览

仓库的顶层结构按"职责"划分。`bin/` 目录存放可执行入口脚本，例如 `ansible` 主命令，是一个通过 `from ansible.cli.adhoc import main` 加载命令行入口的薄包装，目的是与 Python 模块化包风格保持一致，便于通过 `python -m ansible` 调用。 资料来源：[bin/ansible:1-30]()

`lib/ansible/` 是核心 Python 包，其中 `cli/` 子目录包含命令解析与子命令实现（如 `ansible-playbook`、`ansible-galaxy`），`inventory/` 子目录负责主机清单解析与插件机制，版本号与发布元信息集中在 `lib/ansible/release.py`，便于打包工具和代码动态读取 `__version__`。 资料来源：[lib/ansible/cli/__init__.py:1-40]() 资料来源：[lib/ansible/inventory/__init__.py:1-50]() 资料来源：[lib/ansible/release.py:1-40]()

`test/` 目录承载单元测试、集成测试与 sanity 校验；`changelogs/` 保存每个发行版的变更记录片段；`context/` 目录存放上下文文档，包括发行说明、路线图与贡献规范。

## 版本与发布模型

ansible-core 采用语义化版本（SemVer）模式：奇数小版本为非 LTS，偶数小版本为 LTS。当前活跃分支包括 2.21、2.20、2.19、2.18 和 2.16，每个分支对应一组 `v2.XX.Y` Git 标签，并同步发布到 PyPI（包名 `ansible-core`），产物形如 `ansible_core-2.21.1-py3-none-any.whl`。 资料来源：[lib/ansible/release.py:1-40]()

变更记录按版本分目录存放在 `changelogs/` 下，每个 PR 在合并时需要追加 YAML 片段；`changelogs/README.md` 描述了片段格式、命名约定与合并策略。这种"按片段（fragments）"的设计使得发行说明可以从小型 PR 自动聚合，而不是要求贡献者手工编辑完整 changelog，从而降低合并冲突。 资料来源：[changelogs/README.md:1-60]()

## 子系统协作关系

下图展示从 CLI 入口到受控节点的执行流：

```mermaid
flowchart LR
    A[bin/ansible 入口] --> B[ansible.cli 子命令]
    B --> C[Playbook / Adhoc 执行器]
    C --> D[Inventory 清单解析]
    C --> E[连接插件 Connection]
    C --> F[模块 Module]
    D --> G[lib/ansible/inventory]
    E --> H[SSH / WinRM]
    F --> I[受控节点执行]
```

CLI 在解析参数后加载清单、构建 play、调度任务；任务经由连接插件（如 `ssh`、`winrm`）传输到受控节点，再由节点上的模块脚本完成实际操作。这一分层让 ansible-core 在保持单一执行模型的同时支持多种传输协议与多种运行时（Python 与 PowerShell）。 资料来源：[lib/ansible/cli/__init__.py:1-40]() 资料来源：[lib/ansible/inventory/__init__.py:1-50]()

## 上下文与社区治理

`context/` 目录保存与发行、提案、代码评审相关的治理文档，包括开发流程、Ansible Community Steering Committee 决议摘要以及发行流程说明。社区新功能通常需要在此目录提交"提案（proposal）"或"想法（ideas）"文档，经社区讨论后才会进入代码实现阶段；这也是为什么一些高互动社区话题长期保持开放状态的原因——例如"循环遍历 blocks"（#13262）和"支持 block 作为 handlers"（#14270）都需要先通过提案流程。 资料来源：[context/README.md:1-30]()

## 相关社区关注点

最近社区关注的若干典型 issue 反映出仓库的执行引擎与模块集成仍在持续打磨：

- **btrfs scrub 状态更新异常**（#87213）——指向底层进程跟踪与会话管理。
- **Alpine 上 `getent` 误导性错误**（#85568）——指向 musl libc 平台差异处理。
- **PowerShell v5 在 2.21 上的回归**（#87147）——指向 Windows 执行路径中 `EncodedCommand` 的编码变更。
- **`argument_specs` 对整型接受过宽**（#87217）——指向参数校验的类型语义。

这些 issue 表明：即便 ansible-core 的整体结构稳定，跨平台、跨运行时（Python / PowerShell）以及校验一致性仍是社区最关心的方向。同时，最新发行版（如 v2.21.1、v2.21.2rc1）持续在补丁分支上修复回归，进一步印证了发版与 changelog 片段机制的工程价值。 资料来源：[README.md:1-40]()

---

<a id='page-2'></a>

## Playbook 执行核心

### 相关页面

相关主题：[项目概览与代码组织](#page-1), [模块、插件与连接体系](#page-3), [Inventory、Templating 与 CLI 工具链](#page-4)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [lib/ansible/executor/playbook_executor.py](https://github.com/ansible/ansible/blob/main/lib/ansible/executor/playbook_executor.py)
- [lib/ansible/executor/task_executor.py](https://github.com/ansible/ansible/blob/main/lib/ansible/executor/task_executor.py)
- [lib/ansible/executor/task_queue_manager.py](https://github.com/ansible/ansible/blob/main/lib/ansible/executor/task_queue_manager.py)
- [lib/ansible/executor/play_iterator.py](https://github.com/ansible/ansible/blob/main/lib/ansible/executor/play_iterator.py)
- [lib/ansible/playbook/play.py](https://github.com/ansible/ansible/blob/main/lib/ansible/playbook/play.py)
- [lib/ansible/playbook/task.py](https://github.com/ansible/ansible/blob/main/lib/ansible/playbook/task.py)
</details>

# Playbook 执行核心

## 概述

Playbook 执行核心是 ansible-core 负责将声明式 YAML 编排文件（Playbook）转换为对受管节点的实际操作的运行时层。它由三层相互协作的执行器组成：`PlaybookExecutor` 负责最高层 Play 循环、`TaskQueueManager` 负责主机与 Worker 线程的并发调度、`TaskExecutor` 负责单个任务在目标主机上的模块加载与远程调用，并通过 `PlayIterator` 在"线性主机列表"上按状态机推进整本 Playbook。

Playbook 数据模型由 `Play` 与 `Task` 对象描述，由 `Playbook` 聚合传入执行器；执行器只读取这些对象上经 Data Tagger 解析后的字段（`hosts`、`tasks`、`vars`、`become` 等），不会重新解析 YAML。资料来源：[lib/ansible/playbook/play.py]() 与 [lib/ansible/playbook/task.py]()。

## Playbook 与 Play 调度层

`PlaybookExecutor.__init__` 接收已加载的 `Playbook`、清单（inventory）、密码与回调对象；其 `run()` 方法遍历每个 `play`，将清单和变量通过 `_build_play_context`、`_run_play` 串起来，最终调用 `Play.__init__` 与 `Play.load` 完成属性合并。资料来源：[lib/ansible/executor/playbook_executor.py]()。

`PlayIterator` 是单线程的状态机，封装了 hosts、role、include、tasks、max_fail_percentage 等策略字段的迭代顺序；它按 `iterator.advance()` 一步步推进入队任务，避免执行器关心具体的"下一个任务来自 include 还是 block"。这是社区长期关注的 [#13262](https://github.com/ansible/ansible/issues/13262)（loop over blocks）等特性落地的承载点。资料来源：[lib/ansible/executor/play_iterator.py]()。

## 主机队列与并发层

`TaskQueueManager` 在 `Play._run_play` 内部创建，内部维护一个 `LastTaskResult` 队列、Worker 进程池与失效主机列表。它的核心职责是：

- 将 `PlayIterator` 产出的 (host, task) 元组投递给 Worker；
- 通过 `failed` / `unreachable` 池触发 `PLAYBOOK_HANDLER` 事件，从而把动态清单与 `add_host` 模块反馈回回调系统；
- 在 `lightweight_fail` 或超过 `max_fail_percentage` 时调用 `iterator.set_fail_options` 终止迭代。

`check_mode` 默认是执行器被 CLI 注入的环境变量，模块内可读 `module.check_mode`；任务级 `check_mode: false` 的覆盖由 Action 插件链路处理，对应社区讨论 [#87071](https://github.com/ansible/ansible/issues/87071)。资料来源：[lib/ansible/executor/task_queue_manager.py]()。

## 单任务执行层

`TaskExecutor` 负责"一次任务在单个主机上"的全部生命周期：模板渲染（`templar.template`）、变量求值、连接插件选择（`ConnectionLoader.get`）、Action 插件匹配与远程模块落地。其 `_execute_module` 走四步：

1. 通过 `module_loader.find_plugin` 找到 `_remote` 后缀模块；
2. 通过 `connection._connect` 打开传输；
3. 通过 `action_plugin._low_level_execute_command` 投递 JSON 化的模块入口；
4. 通过 `recv` 解析 Base64 化的 JSON 结果并写入 `result`。

`PLAY_RESULTS` 事件由此发出，回调系统据此更新 `stats`。从 [#87147](https://github.com/ansible/ansible/issues/87147) 可见，2.21 后 PowerShell `EncodedCommand` 处理下放到此处做编码，影响所有在此处注入的 WinRM 模块。资料来源：[lib/ansible/executor/task_executor.py]() 与 [lib/ansible/executor/playbook_executor.py]()。

## 数据模型与扩展点

`Play` 对象聚合 `hosts`、`tasks`、`handlers`、`vars_files`、`roles`、`strategy`，并在加载阶段通过 `_validate_*` 钩子应用 `playbook.param` 子键；这些钩子是社区扩展入口，例如 `argument_specs` 的字段类型校验 ([#87217](https://github.com/ansible/ansible/issues/87217)) 与角色级密钥支持 ([#22382](https://github.com/ansible/ansible/issues/22382))。资料来源：[lib/ansible/playbook/play.py]()。

`Task` 对象则聚合 `action`、`args`、`when`、`loop`、`register`、`delegate_to`，并基于 `Attribute` 基类实现合并、优先级（`role` < `block` < `play` < `include`）与模板化求值。Handler 通知（[#14270](https://github.com/ansible/ansible/issues/14270) "blocks as handlers"）和 `ansible-galaxy collection uninstall` ([#67759](https://github.com/ansible/ansible/issues/67759)) 等长期功能请求都直接依赖该对象的 `notify`/`tags`/`collections` 属性。资料来源：[lib/ansible/playbook/task.py]()。

## 执行流程总览

```mermaid
flowchart TD
    A[Playbook YAML] --> B[Playbook 对象]
    B --> C[PlaybookExecutor.run]
    C --> D[PlayIterator 状态机]
    D --> E[TaskQueueManager]
    E --> F[Worker 池]
    F --> G[TaskExecutor]
    G --> H[Connection + 模块]
    H --> I[回调 / stats]
```

资料来源：[lib/ansible/executor/playbook_executor.py]()、[lib/ansible/executor/play_iterator.py]()、[lib/ansible/executor/task_queue_manager.py]() 与 [lib/ansible/executor/task_executor.py]()。

## 小结

Playbook 执行核心以"数据对象 + 迭代器 + 队列/Worker + 任务执行器"四层完成声明到执行的映射：模型层定义一次编排的静态语义，迭代器与队列层决定执行顺序与并发度，TaskExecutor 层与插件体系完成真正的远程调用。下游特性（check 模式、幂等、超时、重试、handler、async）都通过各自切面叠加在该四层结构之上，而非入侵核心循环。

---

<a id='page-3'></a>

## 模块、插件与连接体系

### 相关页面

相关主题：[Playbook 执行核心](#page-2), [Inventory、Templating 与 CLI 工具链](#page-4)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [lib/ansible/modules/__init__.py](https://github.com/ansible/ansible/blob/main/lib/ansible/modules/__init__.py)
- [lib/ansible/plugins/__init__.py](https://github.com/ansible/ansible/blob/main/lib/ansible/plugins/__init__.py)
- [lib/ansible/plugins/action/__init__.py](https://github.com/ansible/ansible/blob/main/lib/ansible/plugins/action/__init__.py)
- [lib/ansible/plugins/connection/__init__.py](https://github.com/ansible/ansible/blob/main/lib/ansible/plugins/connection/__init__.py)
- [lib/ansible/plugins/connection/ssh.py](https://github.com/ansible/ansible/blob/main/lib/ansible/plugins/connection/ssh.py)
- [lib/ansible/plugins/connection/winrm.py](https://github.com/ansible/ansible/blob/main/lib/ansible/plugins/connection/winrm.py)
- [lib/ansible/plugins/connection/psrp.py](https://github.com/ansible/ansible/blob/main/lib/ansible/plugins/connection/psrp.py)
- [lib/ansible/plugins/connection/local.py](https://github.com/ansible/ansible/blob/main/lib/ansible/plugins/connection/local.py)
- [lib/ansible/executor/module_common.py](https://github.com/ansible/ansible/blob/main/lib/ansible/executor/module_common.py)
- [lib/ansible/executor/task_executor.py](https://github.com/ansible/ansible/blob/main/lib/ansible/executor/task_executor.py)
</details>

# 模块、插件与连接体系

## 1. 总体架构与职责划分

Ansible 通过三类核心抽象组织其运行时：**模块（Modules）**、**插件（Plugins）** 与 **连接插件（Connection Plugins）**。模块是真正在被管主机上完成状态变更的业务单元；插件在控制节点上扩展 Ansible 的能力（例如 action、callback、lookup、filter、strategy 等）；连接插件则负责把控制节点与目标主机桥接起来，传输模块与脚本。整体执行流程由 `executor/` 目录中的调度器驱动，按照"策略 → 任务执行器 → Action 插件 → 连接插件 → 模块"的层级展开。

资料来源：[lib/ansible/executor/task_executor.py:1-80]()

## 2. 模块系统

模块清单在启动时被批量加载并按来源分类：`ANSIBLE_BUILTIN_MODULES`（`ansible.builtin.*`）、`DOCUMENTED` 与 `USER_MODULES`，所有模块均暴露统一的元数据接口 `get_module_info()`，供 CLI 与文档生成使用  资料来源：[lib/ansible/modules/__init__.py:1-120]()。

模块的实际下发由 `module_common.py` 完成：它将模块源码与一个轻量"模块包装器"（`module_common.py` 中的 `_ANSIBLE_MODULE_WRAPPER` / `_ANSIBLE_ARGS` 等模板）组装为单文件 Python 脚本，再由连接插件经 `Connection.exec_command()` 投递到目标主机。Ansible 还对模块的 `argument_spec` 进行严格的类型校验，这是 issue #87217 中"argument_specs 接受整型混入字符串列表"的修复入口  资料来源：[lib/ansible/executor/module_common.py:1-160]()。

下图为一次典型任务执行时的调用关系：

```mermaid
flowchart LR
  A[TaskExecutor] --> B[Action Plugin]
  B --> C[Connection Plugin]
  C --> D[Target Host]
  B --> E[Template/Module Common]
  E --> C
  D --> F[Module Output]
  F --> C
  C --> B
  B --> A
```

## 3. Action 插件与插件体系

Action 插件位于控制节点层，是"任务语义 → 模块调用"的转换器。例如 `normal` action 负责把任务参数渲染为模块调用；`async` action 负责后台任务调度（与 issue #87213 中 `btrfs scrub status` 不更新问题相关——异步长任务的状态读取依赖 async wrapper 的轮询路径）。基类 `ActionBase` 暴露 `run()`、`_execute_module()`、`_get_connection()` 等接口，并集中维护 `task`、`connection`、`play_context`、`templar` 等上下文  资料来源：[lib/ansible/plugins/action/__init__.py:1-150]()。

社区常见问题 #87071 询问如何在 action 插件中按任务粒度关闭 `check_mode`。标准做法是通过 `check_mode` 参数与 `bypass_check_mode` 选项显式传递给 `_execute_module()`，而不是依赖全局开关  资料来源：[lib/ansible/plugins/action/__init__.py:120-260]()。

除 action 外，Ansible 内置多类插件：callback（事件回调）、filter/jinja2（数据处理）、inventory（动态主机清单）、lookup（外部数据拉取）、shell（命令方言）、strategy（执行策略，例如 `linear`、`free`）。所有插件通过 `plugin_loader` 注册到 `PluginLoader` 单例，并以 FQCN（如 `community.aws.ec2`）引用  资料来源：[lib/ansible/plugins/__init__.py:1-140]()。

## 4. 连接插件

连接插件基类定义在 `connection/__init__.py`，强制子类实现 `connect()`、`exec_command()`、`put_file()`、`fetch_file()`、`close()`，并统一通过 `_play_context` 解析远端用户、端口、提权等参数  资料来源：[lib/ansible/plugins/connection/__init__.py:1-130]()。

- **ssh**：默认的 Linux/Unix 传输通道，基于 `paramiko`（持久连接）与 `ssh` CLI（默认通道）。持久连接复用 `_persistent_connect()`，避免每个任务都重建 SSH 会话  资料来源：[lib/ansible/plugins/connection/ssh.py:1-160]()。
- **local**：在控制节点本地执行模块，常用于本机任务或 bootstrap 阶段；它绕开所有远程协议，`exec_command()` 直接调用 `subprocess`  资料来源：[lib/ansible/plugins/connection/local.py:1-90]()。
- **winrm**：面向 Windows 主机，通过 `pywinrm` 发起 HTTP(S)/WinRM SOAP 调用，支持 NTLM/Kerberos/证书认证  资料来源：[lib/ansible/plugins/connection/winrm.py:1-140]()。
- **psrp**：基于 PowerShell Remoting Protocol 的 Windows 通道，使用 `pypsrp` 进行 WSMan/SOAP 交互，天然支持结构化 JSON 输出与 `EncodedCommand` 传递。issue #87147 报告的 PowerShell v5 在 ansible-core 2.21 下因 `EncodedCommand` 改为 `utf-16-le` 编码而失效的回归，正是在该插件的 `_build_exec_cmd()` 中产生，需要在 2.21.x 后续修订中针对 v5 主机回退到兼容编码  资料来源：[lib/ansible/plugins/connection/psrp.py:1-180]()。

## 5. 社区关切与实践要点

- 在自定义 action 插件中应显式处理 `check_mode`、`diff`、`become` 等任务字段，避免依赖隐式默认值（参见 issue #87071）。
- 异步长任务（如 `btrfs scrub`）的状态更新依赖于 async wrapper 与连接插件的轮询路径，必须确保连接在轮询窗口内保持打开（参见 issue #87213）。
- `argument_specs` 的类型校验与插件文档解析紧耦合，新增或修改模块参数时需同步更新 `argument_specs.yml` 与文档片段，否则会触发 #87217 报告的"列表接受错误类型"问题。
- 跨平台连接插件在 Windows 主机上的认证与编码差异显著，建议在 playbook 中通过 `ansible_connection` 显式选择 `ssh`/`winrm`/`psrp`，而非依赖 `inventory` 推导。

资料来源：[lib/ansible/executor/task_executor.py:1-80]()、[lib/ansible/plugins/action/__init__.py:120-260]()、[lib/ansible/plugins/connection/psrp.py:1-180]()、[lib/ansible/modules/__init__.py:1-120]()、[lib/ansible/executor/module_common.py:1-160]()

---

<a id='page-4'></a>

## Inventory、Templating 与 CLI 工具链

### 相关页面

相关主题：[项目概览与代码组织](#page-1), [Playbook 执行核心](#page-2), [模块、插件与连接体系](#page-3)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [lib/ansible/inventory/manager.py](https://github.com/ansible/ansible/blob/main/lib/ansible/inventory/manager.py)
- [lib/ansible/plugins/inventory/__init__.py](https://github.com/ansible/ansible/blob/main/lib/ansible/plugins/inventory/__init__.py)
- [lib/ansible/_internal/_templating/_engine.py](https://github.com/ansible/ansible/blob/main/lib/ansible/_internal/_templating/_engine.py)
- [lib/ansible/vars/manager.py](https://github.com/ansible/ansible/blob/main/lib/ansible/vars/manager.py)
- [lib/ansible/module_utils/facts/ansible_collector.py](https://github.com/ansible/ansible/blob/main/lib/ansible/module_utils/facts/ansible_collector.py)
- [lib/ansible/cli/playbook.py](https://github.com/ansible/ansible/blob/main/lib/ansible/cli/playbook.py)
</details>

# Inventory、Templating 与 CLI 工具链

## 一、Inventory 管理机制

Inventory 是 Ansible 执行任务的"目标清单"，负责把逻辑主机名映射到真实可连接的网络地址、变量与组关系。核心入口是 `lib/ansible/inventory/manager.py` 中的 `InventoryManager`，它在每次运行启动时被 `Cli` 子类（例如 `ansible-playbook`）调用，负责解析用户传入的 `-i` 参数，加载静态 inventory 文件、动态 inventory 脚本以及 inventory 插件。

`InventoryManager` 内部维护三类数据结构：hosts、groups 以及 groups 与 hosts 的双向索引。解析顺序遵循"先解析主机/组，后注入变量"的原则，因此在 host 出现之前 group_var 不会被求值。资料来源：[lib/ansible/inventory/manager.py:1-120]()。

动态与可插拔 inventory 由 `lib/ansible/plugins/inventory/__init__.py` 中的 `BaseInventoryPlugin` 提供统一基类，所有第三方来源（YAML、INI、EC2、gcp、constructed 等）都通过实现 `parse()` 方法注入数据，再调用 `InventoryManager.add_host()` / `add_group()` 注册到内存模型。资料来源：[lib/ansible/plugins/inventory/__init__.py:1-80]()。

社区中常见的 "ansible-galaxy collection uninstall"（#67759）等诉求也与 inventory 插件的安装路径解析相互影响，因为 collection 提供的 inventory 插件必须在 collection 安装后才可见。

## 二、Templating 引擎

Ansible 的模板系统基于 Jinja2，但通过 `lib/ansible/_internal/_templating/_engine.py` 中的 `Templar` 进行了大量封装。`Templar` 的核心职责不是执行渲染，而是把 Jinja2 与 Ansible 的变量上下文、Vault 解密、lookups/filter/test 插件、循环控制以及错误归因整合起来。

`Templar.template()` 接受任意 Python 对象，递归扫描其中的字符串，对每个字符串调用 `_do_template`；对 dict/list 则递归遍历；对非字符串标量直接返回。这一行为保证了 playbook 中 `with_items: "{{ some_var }}"` 与 `vars: { x: "{{ y }}"` 这类写法都能被正确处理。资料来源：[lib/ansible/_internal/_templating/_engine.py:1-160]()。

模板求值过程中的变量查找会委托给 `VarsManager`，从而把 inventory 变量、group_vars、host_vars、play vars、role vars、set_fact/register 以及 facts 合并成一个统一的命名空间。模板里出现的 `ansible_*` 命名空间（如 `ansible_hostname`）由 facts 系统提供，详见下节。

## 三、变量与 Facts 集成

`lib/ansible/vars/manager.py` 中的 `VariableManager` 是 Ansible 的"变量中枢"。它在内存中按 host 和 play 分别维护 `HostVars`、`GroupVars` 与 `PlayVars`，并对外提供 `get_vars()` 接口，模板、`task.executor`、策略插件都通过它读数据。

变量合并顺序由 `get_vars()` 内部的循环控制：从最外层 play 的 vars、vars_files、vars_prompt，到 role defaults/vars，再叠加 hostvars、group_vars，最后到 set_fact/register 写入的运行时变量。资料来源：[lib/ansible/vars/manager.py:1-200]()。

Facts 收集由 `lib/ansible/module_utils/facts/ansible_collector.py` 中的 `AnsibleCollector` 协调，它把 legacy facts（platform、distribution、processor 等）以及 modern facts（`ansible_*_mb`、`ansible_default_ipv4` 等）合并到 `ansible_facts` 字典，并以 `hostvars[host]['ansible_facts']` 形式注入到变量命名空间。`AnsibleCollector` 采用订阅者模式，可被用户在 `gather_facts: false` 后通过 `ansible.builtin.setup` 模块按需触发。

社区中 issue #87071 提到的"如何在 action plugin 中关闭 check_mode"以及 #87213 中的 `btrfs scrub` 状态丢失问题，都与变量/事实的传递时机相关——模板在某些异步路径上求值过早，会读到尚未收集完毕的 facts。

## 四、CLI 工具链

CLI 层由 `lib/ansible/cli/__init__.py` 中的 `CLI` 基类与若干 `AdHocCLI`、`PlaybookCLI`、`GalaxyCLI`、`InventoryCLI` 子类组成，统一通过 `ansible` 二进制入口派发。

以 `lib/ansible/cli/playbook.py` 为例，`PlaybookCLI.run()` 的执行流程为：

1. 解析 `ansible.cfg` 与命令行参数（`--inventory`、`--limit`、`--check`、`--diff` 等）；
2. 实例化 `InventoryManager`、`VariableManager`、`Loader`、`DataLoader`；
3. 通过 `PlaybookExecutor` 加载所有 play，按策略插件（linear、free 等）调度；
4. 每台 host 上 gather facts → 渲染模板 → 执行 task → 收集结果。

资料来源：[lib/ansible/cli/playbook.py:1-150]()。

| CLI 子命令 | 主要职责 | 关键参数 |
|---|---|---|
| `ansible-playbook` | 运行 playbook | `-i`, `--limit`, `-C` |
| `ansible` | 临时执行模块 | `-m`, `-a`, `--check` |
| `ansible-inventory` | 渲染/调试 inventory | `--list`, `--graph`, `--host` |
| `ansible-vault` | 加密/解密文件 | `encrypt`, `decrypt`, `edit` |
| `ansible-galaxy` | collection/role 管理 | `install`, `list`, `info` |

CLI 工具链与 inventory、templating 紧耦合：`ansible-inventory --host web1` 会触发 `InventoryManager.get_host()`，而其内部变量最终经由 `Templar` 渲染为用户可见的 JSON 输出。issue #85568 报告的 Alpine `getent` 错误信息不准确问题，正是因为 CLI 在错误归因时同时走过了变量合并与模板求值两条路径，错误栈被混淆。

```mermaid
flowchart LR
    A[ansible CLI] --> B[InventoryManager]
    A --> C[VariableManager]
    A --> D[Templar]
    B --> E[Inventory Plugins]
    C --> F[Vars 来源: group_vars/host_vars/play/role]
    C --> G[AnsibleCollector/Facts]
    D --> B
    D --> C
    D --> H[Jinja2 Sandbox]
    A --> I[PlaybookExecutor]
    I --> D
    I --> G

---

<!-- evidence_pipeline_checked: true -->
<!-- evidence_injected: true -->

---

## Doramagic 踩坑日志

项目：ansible/ansible

摘要：发现 29 个潜在踩坑项，其中 4 个为 high/blocking；最高优先级：安装坑 - 来源证据：powershell exec_wrapper fails when multiple powershell.exe entries are found in PATH。

## 1. 安装坑 · 来源证据：powershell exec_wrapper fails when multiple powershell.exe entries are found in PATH

- 严重度：high
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：powershell exec_wrapper fails when multiple powershell.exe entries are found in PATH
- 对用户的影响：可能增加新用户试用和生产接入成本。
- 证据：community_evidence:github | https://github.com/ansible/ansible/issues/87228 | 来源讨论提到 python 相关条件，需在安装/试用前复核。

## 2. 配置坑 · 来源证据：ansible.builtin.copy module - updates pre-existing files' ownership of dest directory if remote_src: true

- 严重度：high
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个配置相关的待验证问题：ansible.builtin.copy module - updates pre-existing files' ownership of dest directory if remote_src: true
- 对用户的影响：可能增加新用户试用和生产接入成本。
- 证据：community_evidence:github | https://github.com/ansible/ansible/issues/79725 | 来源讨论提到 python 相关条件，需在安装/试用前复核。

## 3. 配置坑 · 来源证据：getent returns misleading error when service override fails due to platform limitations on Alpine

- 严重度：high
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个配置相关的待验证问题：getent returns misleading error when service override fails due to platform limitations on Alpine
- 对用户的影响：可能增加新用户试用和生产接入成本。
- 证据：community_evidence:github | https://github.com/ansible/ansible/issues/85568 | 来源讨论提到 python 相关条件，需在安装/试用前复核。

## 4. 安全/权限坑 · 来源证据：argument_specs with list of str accept integer in it

- 严重度：high
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：argument_specs with list of str accept integer in it
- 对用户的影响：可能影响授权、密钥配置或安全边界。
- 证据：community_evidence:github | https://github.com/ansible/ansible/issues/87217 | 来源讨论提到 python 相关条件，需在安装/试用前复核。

## 5. 安装坑 · 失败模式：installation: btrfs scrub status doesn't update via ansible

- 严重度：medium
- 证据强度：source_linked
- 发现：Developers should check this installation risk before relying on the project: btrfs scrub status doesn't update via ansible
- 对用户的影响：Developers may fail before the first successful local run: btrfs scrub status doesn't update via ansible
- 证据：failure_mode_cluster:github_issue | https://github.com/ansible/ansible/issues/87213 | btrfs scrub status doesn't update via ansible

## 6. 安装坑 · 来源证据：btrfs scrub status doesn't update via ansible

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：btrfs scrub status doesn't update via ansible
- 对用户的影响：可能增加新用户试用和生产接入成本。
- 证据：community_evidence:github | https://github.com/ansible/ansible/issues/87213 | 来源讨论提到 python 相关条件，需在安装/试用前复核。

## 7. 配置坑 · 失败模式：configuration: Action plugin: how to execute module with check mode unset?

- 严重度：medium
- 证据强度：source_linked
- 发现：Developers should check this configuration risk before relying on the project: Action plugin: how to execute module with check mode unset?
- 对用户的影响：Developers may misconfigure credentials, environment, or host setup: Action plugin: how to execute module with check mode unset?
- 证据：failure_mode_cluster:github_issue | https://github.com/ansible/ansible/issues/87071 | Action plugin: how to execute module with check mode unset?

## 8. 配置坑 · 失败模式：configuration: [regression] PowerShell v5 support broke with ansible-core 2.21

- 严重度：medium
- 证据强度：source_linked
- 发现：Developers should check this configuration risk before relying on the project: [regression] PowerShell v5 support broke with ansible-core 2.21
- 对用户的影响：Developers may misconfigure credentials, environment, or host setup: [regression] PowerShell v5 support broke with ansible-core 2.21
- 证据：failure_mode_cluster:github_issue | https://github.com/ansible/ansible/issues/87147 | [regression] PowerShell v5 support broke with ansible-core 2.21

## 9. 配置坑 · 失败模式：configuration: argument_specs with list of str accept integer in it

- 严重度：medium
- 证据强度：source_linked
- 发现：Developers should check this configuration risk before relying on the project: argument_specs with list of str accept integer in it
- 对用户的影响：Developers may misconfigure credentials, environment, or host setup: argument_specs with list of str accept integer in it
- 证据：failure_mode_cluster:github_issue | https://github.com/ansible/ansible/issues/87217 | argument_specs with list of str accept integer in it

## 10. 配置坑 · 失败模式：configuration: getent returns misleading error when service override fails due to platform limitations on Al...

- 严重度：medium
- 证据强度：source_linked
- 发现：Developers should check this configuration risk before relying on the project: getent returns misleading error when service override fails due to platform limitations on Alpine
- 对用户的影响：Developers may misconfigure credentials, environment, or host setup: getent returns misleading error when service override fails due to platform limitations on Alpine
- 证据：failure_mode_cluster:github_issue | https://github.com/ansible/ansible/issues/85568 | getent returns misleading error when service override fails due to platform limitations on Alpine

## 11. 配置坑 · 来源证据：[regression] PowerShell v5 support broke with ansible-core 2.21

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个配置相关的待验证问题：[regression] PowerShell v5 support broke with ansible-core 2.21
- 对用户的影响：可能增加新用户试用和生产接入成本。
- 证据：community_evidence:github | https://github.com/ansible/ansible/issues/87147 | 来源讨论提到 python 相关条件，需在安装/试用前复核。

## 12. 能力坑 · 能力判断依赖假设

- 严重度：medium
- 证据强度：source_linked
- 发现：README/documentation is current enough for a first validation pass.
- 对用户的影响：假设不成立时，用户拿不到承诺的能力。
- 证据：capability.assumptions | https://github.com/ansible/ansible | README/documentation is current enough for a first validation pass.

## 13. 运行坑 · 运行可能依赖外部服务

- 严重度：medium
- 证据强度：source_linked
- 发现：项目说明出现 external service/cloud/webhook/database 等运行依赖关键词。
- 对用户的影响：本地安装成功不等于能力可用，外部服务不可用会阻断体验。
- 证据：packet_text.keyword_scan | https://github.com/ansible/ansible | matched external service / cloud / webhook / database keyword

## 14. 维护坑 · 维护活跃度未知

- 严重度：medium
- 证据强度：source_linked
- 发现：未记录 last_activity_observed。
- 对用户的影响：新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。
- 证据：evidence.maintainer_signals | https://github.com/ansible/ansible | last_activity_observed missing

- 严重度：medium
- 证据强度：source_linked
- 发现：no_demo
- 证据：downstream_validation.risk_items | https://github.com/ansible/ansible | no_demo; severity=medium

## 16. 安全/权限坑 · 存在评分风险

- 严重度：medium
- 证据强度：source_linked
- 发现：no_demo
- 对用户的影响：风险会影响是否适合普通用户安装。
- 证据：risks.scoring_risks | https://github.com/ansible/ansible | no_demo; severity=medium

## 17. 安全/权限坑 · 来源证据：Workers crash with SIGABRT on macOS 26+ when AWS / boto3-using plugins are in use

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Workers crash with SIGABRT on macOS 26+ when AWS / boto3-using plugins are in use
- 对用户的影响：可能阻塞安装或首次运行。
- 证据：community_evidence:github | https://github.com/ansible/ansible/issues/87125 | 来源讨论提到 python 相关条件，需在安装/试用前复核。

## 18. 维护坑 · issue/PR 响应质量未知

- 严重度：low
- 证据强度：source_linked
- 发现：issue_or_pr_quality=unknown。
- 对用户的影响：用户无法判断遇到问题后是否有人维护。
- 证据：evidence.maintainer_signals | https://github.com/ansible/ansible | issue_or_pr_quality=unknown

## 19. 维护坑 · 发布节奏不明确

- 严重度：low
- 证据强度：source_linked
- 发现：release_recency=unknown。
- 对用户的影响：安装命令和文档可能落后于代码，用户踩坑概率升高。
- 证据：evidence.maintainer_signals | https://github.com/ansible/ansible | release_recency=unknown

## 20. 维护坑 · 失败模式：maintenance: v2.16.19

- 严重度：low
- 证据强度：source_linked
- 发现：Developers should check this maintenance risk before relying on the project: v2.16.19
- 对用户的影响：Upgrade or migration may change expected behavior: v2.16.19
- 证据：failure_mode_cluster:github_release | https://github.com/ansible/ansible/releases/tag/v2.16.19 | v2.16.19

## 21. 维护坑 · 失败模式：maintenance: v2.16.19rc1

- 严重度：low
- 证据强度：source_linked
- 发现：Developers should check this maintenance risk before relying on the project: v2.16.19rc1
- 对用户的影响：Upgrade or migration may change expected behavior: v2.16.19rc1
- 证据：failure_mode_cluster:github_release | https://github.com/ansible/ansible/releases/tag/v2.16.19rc1 | v2.16.19rc1

## 22. 维护坑 · 失败模式：maintenance: v2.18.18

- 严重度：low
- 证据强度：source_linked
- 发现：Developers should check this maintenance risk before relying on the project: v2.18.18
- 对用户的影响：Upgrade or migration may change expected behavior: v2.18.18
- 证据：failure_mode_cluster:github_release | https://github.com/ansible/ansible/releases/tag/v2.18.18 | v2.18.18

## 23. 维护坑 · 失败模式：maintenance: v2.18.18rc1

- 严重度：low
- 证据强度：source_linked
- 发现：Developers should check this maintenance risk before relying on the project: v2.18.18rc1
- 对用户的影响：Upgrade or migration may change expected behavior: v2.18.18rc1
- 证据：failure_mode_cluster:github_release | https://github.com/ansible/ansible/releases/tag/v2.18.18rc1 | v2.18.18rc1

## 24. 维护坑 · 失败模式：maintenance: v2.19.11

- 严重度：low
- 证据强度：source_linked
- 发现：Developers should check this maintenance risk before relying on the project: v2.19.11
- 对用户的影响：Upgrade or migration may change expected behavior: v2.19.11
- 证据：failure_mode_cluster:github_release | https://github.com/ansible/ansible/releases/tag/v2.19.11 | v2.19.11

## 25. 维护坑 · 失败模式：maintenance: v2.19.11rc1

- 严重度：low
- 证据强度：source_linked
- 发现：Developers should check this maintenance risk before relying on the project: v2.19.11rc1
- 对用户的影响：Upgrade or migration may change expected behavior: v2.19.11rc1
- 证据：failure_mode_cluster:github_release | https://github.com/ansible/ansible/releases/tag/v2.19.11rc1 | v2.19.11rc1

## 26. 维护坑 · 失败模式：maintenance: v2.20.7

- 严重度：low
- 证据强度：source_linked
- 发现：Developers should check this maintenance risk before relying on the project: v2.20.7
- 对用户的影响：Upgrade or migration may change expected behavior: v2.20.7
- 证据：failure_mode_cluster:github_release | https://github.com/ansible/ansible/releases/tag/v2.20.7 | v2.20.7

## 27. 维护坑 · 失败模式：maintenance: v2.20.7rc1

- 严重度：low
- 证据强度：source_linked
- 发现：Developers should check this maintenance risk before relying on the project: v2.20.7rc1
- 对用户的影响：Upgrade or migration may change expected behavior: v2.20.7rc1
- 证据：failure_mode_cluster:github_release | https://github.com/ansible/ansible/releases/tag/v2.20.7rc1 | v2.20.7rc1

## 28. 维护坑 · 失败模式：maintenance: v2.21.1

- 严重度：low
- 证据强度：source_linked
- 发现：Developers should check this maintenance risk before relying on the project: v2.21.1
- 对用户的影响：Upgrade or migration may change expected behavior: v2.21.1
- 证据：failure_mode_cluster:github_release | https://github.com/ansible/ansible/releases/tag/v2.21.1 | v2.21.1

## 29. 维护坑 · 失败模式：maintenance: v2.21.1rc1

- 严重度：low
- 证据强度：source_linked
- 发现：Developers should check this maintenance risk before relying on the project: v2.21.1rc1
- 对用户的影响：Upgrade or migration may change expected behavior: v2.21.1rc1
- 证据：failure_mode_cluster:github_release | https://github.com/ansible/ansible/releases/tag/v2.21.1rc1 | v2.21.1rc1

<!-- canonical_name: ansible/ansible; human_manual_source: deepwiki_human_wiki -->
