You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ansible如何设置仅当所有指定目标主机均可达时才执行task/role

Ansible 执行条件配置方案

完全可以实现你需要的两类执行控制逻辑,具体配置方式如下:

1. 仅当所有关联目标主机全部可达时执行角色

先在play中添加前置可达性探测逻辑,再给角色绑定判断条件:

- hosts: backend:cluster
  gather_facts: no
  pre_tasks:
    # 探测所有目标主机存活状态
    - name: 检测主机可达性
      ansible.builtin.ping:
      register: ping_res
      ignore_unreachable: yes
      ignore_errors: yes

    # 统计不可达主机数量,单节点执行一次即可
    - name: 统计不可达主机数
      ansible.builtin.set_fact:
        unreachable_hosts_count: "{{ ansible_play_hosts_all | difference(ansible_play_hosts) | length }}"
      run_once: yes

  roles:
    - role: install_keys
      # 仅当无不可达主机时才执行角色
      when: unreachable_hosts_count | int == 0

2. 仅当执行范围未被--limit限制为单组时执行角色

你需要的--limit "backend"时自动跳过角色的需求,可以通过判断当前执行范围是否同时覆盖backend和cluster两个组实现:

- hosts: backend:cluster
  gather_facts: no
  pre_tasks:
    - name: 判断执行范围是否同时包含两个主机组
      ansible.builtin.set_fact:
        has_both_groups: "{{ groups.backend | intersect(ansible_play_batch) | length > 0 and groups.cluster | intersect(ansible_play_batch) | length > 0 }}"
      run_once: yes

  roles:
    - role: install_keys
      when: has_both_groups | bool

如果需要只要用--limit缩小了任意范围就跳过角色,可以直接对比当前执行主机列表和原始组的全量列表:

when: ansible_play_hosts_all | sort == (groups['backend'] + groups['cluster']) | unique | sort

内容的提问来源于stack exchange,提问作者Arctick

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 00:18:02