当该组中的一个节点关闭时,该组中的主机上的 Jinja2 循环会失败

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

我有这段代码

---
- name: gather facts
  hosts: all

- hosts: proxy

  tasks:

    - blockinfile:
        path: /etc/example
        block: |
          {% for n in groups['all'] %}
          {{ hostvars[n]['ansible_default_ipv4']['address'] }}
          {% endfor %}

如果组

all
中的一个节点发生故障,则 Jinja2 循环失败。

我没有找到解决方案来防止这种情况(例如尝试使用

skip_unreachable: true
但没有成功)。当然,我可以评论库存中的下一个节点,但这既不方便也不可靠。

我怎样才能防止这种情况发生?

loops ansible jinja2 ansible-facts
1个回答
0
投票

对于内容为

的库存
[test]
one.example.com
two.example.com

[proxy]
one.example.com

一个最小的示例手册

---
- hosts: all
  become: false
  gather_facts: true
  gather_subset:
    - '!min'
    - '!all'
    - 'network'

  tasks:

  - debug:
      var: ansible_play_hosts

  - set_fact:
      reachable: "{{ ansible_play_hosts }}"

- hosts: proxy
  gather_facts: false

  tasks:

  - debug:
      msg: |
        {% for n in reachable %}
        {{ hostvars[n]['ansible_default_ipv4']['address'] }}
        {% endfor %}

将产生

的输出
PLAY [all] **********************************************************

TASK [Gathering Facts] **********************************************
fatal: [two.example.com]: UNREACHABLE! => changed=false
  msg: 'Failed to connect to the host via ssh: ssh: <omitted>'
  unreachable: true
ok: [one.example.com]

TASK [debug] ********************************************************
ok: [one.example.com] =>
  ansible_play_hosts:
  - one.example.com

TASK [set_fact] *****************************************************
ok: [one.example.com]

PLAY [proxy] ********************************************************

TASK [debug] ********************************************************
ok: [one.example.com] =>
  ansible_play_hosts:
  - one.example.com

TASK [debug] ********************************************************
ok: [one.example.com] =>
  msg: |-
    192.0.2.1

PLAY RECAP **********************************************************
one.example.com : ok=4    changed=0    unreachable=0    
two.example.com : ok=0    changed=0    unreachable=1

类似的问答和文档

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