gpt4 book ai didi

loops - 我如何遍历 Ansible 中通配符标识的主机

转载 作者:行者123 更新时间:2023-12-04 08:12:25 31 4
gpt4 key购买 nike

下面是我的剧本,效果很好。

---
- 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也有效。

    关于loops - 我如何遍历 Ansible 中通配符标识的主机,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65886304/

    31 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com