wait_for_connection 是 ansible 中专为等待目标主机 ssh 完全就绪而设计的模块,通过建立真实 ssh 连接并执行 echo 命令验证通信能力,避免 ping 或 wait_for 的局限性。

wait_for_connection 是 Ansible 中专为「等待目标主机 SSH 连通并准备好接收任务」而设计的模块,特别适合大规模扩容场景——新机器刚上线、系统初始化未完成、SSH 服务刚启动但 Python 环境/权限尚未就绪时,直接跑 ping 或 command 模块容易失败。它不检查端口或 HTTP,而是真正尝试建立一次完整的 SSH 连接 + 执行一个极简探测命令(如 echo),确认控制节点能稳定通信。
为什么不用 ping 或 wait_for?
-
ping模块依赖远程 Python 和ansible运行环境,新机器可能还没装 Python 或/usr/bin/python3不在预期路径; -
wait_for检查 TCP 端口通了就返回,但 SSH daemon 虽已监听,可能仍卡在密钥加载、PAM 初始化或 SELinux 上下文设置中,后续任务会因连接中断失败; -
wait_for_connection是唯一一个主动模拟真实任务执行链路的等待模块:建 SSH 连接 → 认证 → 执行echo→ 解析返回 → 判定“可接管”。
正确用法:基础等待 + 合理超时
在 Playbook 开头加入该任务,确保后续所有操作都基于已就绪的连接:
- name: Wait for SSH to be fully ready on new nodes
wait_for_connection:
timeout: 300
delay: 10
sleep: 5
说明:
-
timeout: 300:最长等 5 分钟(新云主机首次启动、磁盘初始化、cloud-init 完成常需 1–3 分钟); -
delay: 10:首次探测前等待 10 秒(避免刚开机 SSH 还没监听); -
sleep: 5:每次失败后休眠 5 秒再重试(避免高频探测触发防火墙限速或 sshd 的 connection throttling)。
⚠️ 注意:该模块默认使用 inventory 中定义的
ansible_user、ansible_ssh_private_key_file、ansible_port等参数,务必确保这些已在 host vars 或组 vars 中显式声明(例如web01 ansible_host=192.168.1.100 ansible_user=ubuntu ansible_ssh_private_key_file=~/.ssh/id_rsa_ubuntu)。
配合 facts 收集做二次校验(推荐)
单纯连通不等于可用。建议紧随其后加一个轻量 facts 收集任务,验证 Python 路径和基础环境:
- name: Gather minimal facts to confirm Python & interpreter readiness
setup:
gather_subset: min
become: false
如果这一步失败(比如报 module_stderr: /usr/bin/python3: not found),说明需先通过 raw 模块安装 Python:
Zynq‑7000 / Zynq UltraScale+ 硬件调试技能。适用于 Xilinx Zynq(Cortex‑A9/A53 + FPGA)Linux 环境,调试 I2C、I2S、UART、GPIO 等外设。包括设备树配置、内核驱动、用户空间调试工具、交叉编译和常见问题排查,支持 PetaLinux 开发。
- name: Install Python3 if missing (for Ubuntu/Debian)
raw: apt-get update && apt-get install -y python3 && ln -sf python3 /usr/bin/python
when: ansible_facts['python_version'] is not defined or ansible_facts['python_version'].split('.')[0] != '3'
ignore_errors: true
- name: Retry fact gathering after Python install
setup:
gather_subset: min
become: false
大规模并发下的关键调优
面对上百台新节点同时上线,Ansible 默认并发数(forks=5)会导致排队等待、整体耗时翻倍:
-
在
ansible.cfg中调高并发:[defaults] forks = 50 host_key_checking = False retry_files_enabled = False [ssh_connection] pipelining = True ssh_args = -o ControlMaster=auto -o ControlPersist=60s
-
使用
--limit分批执行(例如每批 20 台):ansible-playbook site.yml -i inventories/prod.yml --limit '@batch1'
-
Inventory 中为新节点打标签,便于精准调度:
[new_nodes] node-001.example.com ansible_host=10.0.1.101 node-002.example.com ansible_host=10.0.1.102 [new_nodes:vars] ansible_python_interpreter=/usr/bin/python3
不复杂但容易忽略。










