我如何循环遍历 Ansible 中由通配符标识的主机
How do i loop over hosts identified by wildcards in Ansible
下面是我的剧本,效果很好。
---
- hosts: "PROD_SERVERS"
user: "{{USER}}"
tasks:
- name: Check if all hosts are reachable
fail:
msg: "Server is UNREACHABLE."
when: "hostvars[item].ansible_facts|list|length == 0"
with_items: "{{ groups.PROD_SERVERS }}"
但是,当主机显示为通配符时,您能帮我解决语法问题吗?{{ENV}}_*
?
---
- hosts: "{{ENV}}_*"
user: "{{USER}}"
tasks:
- name: Check if all hosts are reachable
fail:
msg: "Server is UNREACHABLE."
when: "hostvars[item].ansible_facts|list|length == 0"
with_items: "{{ groups.{{ENV}}_* }}" <------- Need help with this part of the code
有special variables也被称为“魔法变量”来识别当前播放的主机。他们是:
ansible_play_hosts
ansible_play_batch
您可以使用这些变量之一代替库存组名称进行循环。
示例ansible_play_hosts
:
- fail:
msg: "Server is UNREACHABLE."
when: hostvars[item].ansible_facts|list|length == 0
with_items: "{{ ansible_play_hosts }}"
更新:
更改了 Ansible 版本“2.4.x”的示例,应使用 with_items
而不是 loop
执行循环。引用自 official documentation
We added loop
in Ansible 2.5. It is not yet a full replacement for with_<lookup>
, but we recommend it for most use cases.
注意:对于 Ansible“2.9.16”和“2.10.2”loop
也适用。
下面是我的剧本,效果很好。
---
- hosts: "PROD_SERVERS"
user: "{{USER}}"
tasks:
- name: Check if all hosts are reachable
fail:
msg: "Server is UNREACHABLE."
when: "hostvars[item].ansible_facts|list|length == 0"
with_items: "{{ groups.PROD_SERVERS }}"
但是,当主机显示为通配符时,您能帮我解决语法问题吗?{{ENV}}_*
?
---
- hosts: "{{ENV}}_*"
user: "{{USER}}"
tasks:
- name: Check if all hosts are reachable
fail:
msg: "Server is UNREACHABLE."
when: "hostvars[item].ansible_facts|list|length == 0"
with_items: "{{ groups.{{ENV}}_* }}" <------- Need help with this part of the code
有special variables也被称为“魔法变量”来识别当前播放的主机。他们是:
ansible_play_hosts
ansible_play_batch
您可以使用这些变量之一代替库存组名称进行循环。
示例ansible_play_hosts
:
- fail:
msg: "Server is UNREACHABLE."
when: hostvars[item].ansible_facts|list|length == 0
with_items: "{{ ansible_play_hosts }}"
更新:
更改了 Ansible 版本“2.4.x”的示例,应使用 with_items
而不是 loop
执行循环。引用自 official documentation
We added
loop
in Ansible 2.5. It is not yet a full replacement forwith_<lookup>
, but we recommend it for most use cases.
注意:对于 Ansible“2.9.16”和“2.10.2”loop
也适用。