变量 with_items 和 hostvars

问题描述 投票:0回答:1

我需要传递一个动态组名称信息 with_items ,以便我可以访问从另一台主机运行的特定事实。我无法硬编码组名称

我尝试设置一个通用变量,以几种不同的方式作为“GroupName”传递。包括

with_items: "{{ groups['{{GROUPNAME}}'] }}"

   - name: Name of task
     debug:
       msg: "{{ hostvars[item]['ansible_check_mode'] }}"
     with_items: "{{ groups['GROUPNAME'] }}"

致命:[localhost]:失败! => {"msg": "'dict object' 没有属性 '{{ GROUPNAME }}'"}

ansible ansible-2.x ansible-facts
1个回答
2
投票

更新

不要在任何引号或卷曲中关闭变量GROUPNAME

groups[GROUPNAME]
例如,给出以下库存

shell> cat hosts [group_A] host_1 host_2 host_3 [group_B] host_4 host_5 [group_C] host_6 host_7 host_8
这部剧

shell> cat pb.yml - hosts: all tasks: - debug: msg: "{{ item }}" loop: "{{ groups[GROUPNAME] }}" run_once: true - debug: msg: "{{ hostvars[item]['ansible_check_mode'] }}" loop: "{{ groups[GROUPNAME] }}" run_once: true
给出(删节)

shell> ansible-playbook pb.yml -e GROUPNAME=group_B ... TASK [debug] ********************************************************************************* ok: [host_1] => (item=host_4) => msg: host_4 ok: [host_1] => (item=host_5) => msg: host_5 TASK [debug] ********************************************************************************* ok: [host_1] => (item=host_4) => msg: false ok: [host_1] => (item=host_5) => msg: false
当你在检查模式下运行游戏时,你应该得到

shell> ansible-playbook pb.yml -e GROUPNAME=group_B --check ... TASK [debug] ********************************************************************************* ok: [host_1] => (item=host_4) => msg: true ok: [host_1] => (item=host_5) => msg: true


起源

获取组内主机列表并循环它们

vars: my_group: GROUPNAME tasks: - set_fact: my_hosts: "{{ groups| dict2items| selectattr('key', 'match', my_group)| map(attribute='value')| list| flatten }}" - debug: msg: "{{ hostvars[item]['ansible_check_mode'] }}" loop: "{{ my_hosts }}"
(未测试)

© www.soinside.com 2019 - 2024. All rights reserved.