Ansible中group_by生成的动态组值累加,如何覆盖旧值保留新主机
问题原因
同一个ansible-playbook运行进程中,动态组信息是全局共享的,两次调用group_by使用相同的key值reachable_other_pairs时,新的符合条件的主机会被追加到已有组中,不会覆盖原有组内容,因此会出现A、B侧可达主机合并的现象。
解决方案
方案1:使用独立的动态组key(最推荐)
将A侧和B侧的group_by key分开定义,完全避免冲突,无需额外处理逻辑:
- A侧检测的group_by配置改为:
- name: Add devices with connectivity to the side A reachable group group_by: key: "reachable_side_a"
- B侧检测的group_by配置改为:
- name: Add devices with connectivity to the side B reachable group group_by: key: "reachable_side_b"
后续需要使用B侧可达主机时,直接调用groups['reachable_side_b']即可得到目标结果。
方案2:从合并组中过滤B侧主机
如果必须保留同一个动态组key,可以利用B侧主机名的统一特征(含hb标识)做Jinja2过滤:
- name: 筛选仅B侧可达主机 set_fact: reachable_b_hosts: "{{ groups['reachable_other_pairs'] | select('search', 'hb') | list }}" run_once: yes
执行后reachable_b_hosts变量的值就是你需要的['testhb1', 'testhb2', 'testhb3']。
方案3:B侧检测前清空原有动态组
在B侧可达性检测的play开头,先重置原有动态组的内容,再执行后续检测逻辑:
- name: check reachable side B hosts hosts: ????hb??? connection: local gather_facts: no roles: - Juniper.junos vars: credentials: host: "{{ loopback_v4 }}" username: "test" ssh_keyfile: "/id_rsa" port: "{{ port }}" timeout: 60 tasks: - name: 清空原有动态组内容 set_fact: groups: "{{ groups | combine({'reachable_other_pairs': []}) }}" run_once: yes - block: - name: "Check netconf connectivity with switches" juniper_junos_ping: provider: "{{ credentials }}" dest: "{{ loopback_v4 }}" - name: Add devices with connectivity to the "reachable" group group_by: key: "reachable_other_pairs" rescue: - debug: msg="Cannot ping to {{inventory_hostname}}. Skipping OS Install"
执行后groups['reachable_other_pairs']就仅包含本次B侧检测得到的可达主机。
内容的提问来源于stack exchange,提问作者senthil
相关产品推荐
相关产品推荐

