ansible-当只有一个主机满足条件时,为所有正在运行的主机设置事实

时间:2020-08-27 15:10:10

标签: ansible

使用Ansible v2.9.12

问题:当至少一台主机满足特定条件时,如何为剧中的所有主机设置变量。

示例:

- hosts:
    - host1
    - host2
    - host3
    - host4
  tasks:
    - stat:
        path: /tmp/file
      register: something

    - set_fact
        something: true
      when: something <at least one of the hosts has /tmp/file>
 

现在,只有host4的文件系统中包含/tmp/file。在这种情况下,如何为所有主机设置事实?

1 个答案:

答案 0 :(得分:1)

在弗拉基米尔·博特卡(Vladimir Botka)的帮助下:

---
- hosts:
    - test-multi-03
    - test-multi-02
    - test-multi-01
  tasks:
    - name: stat file
      stat:
        path: /tmp/file
      register: status

    - block:

        - name: create dictionary
          set_fact:
            status: "{{ dict(keys|zip(values)) }}"
          vars:
            keys: "{{ ansible_play_hosts }}"
            values: "{{ ansible_play_hosts|
                        map('extract', hostvars, ['status','stat','exists'])
                        | list }}"

        - name: set fact when file is present on at least one host, for all hosts
          set_fact:
            something: yeah
          when: status.values() | list is any

      run_once: true

    - debug:
        msg: "{{ something }}"
      when: something is defined