Search code examples
ansibleansible-facts

How can I accumulate data of multiple hosts and process it at once in Ansible?


I want to collect data from multiple hosts and process it at once afterwards, e. g. comparing data of one host with the data of the other hosts. This is what I tried:

- name: Play 1
  hosts: multiplehosts
  gather_facts: no
  tasks:
    - name: Accumulate data
      ansible.builtin.set_fact:
        data: '{{ data | default([]) + [''foobar''] }}'
      delegate_to: localhost
      delegate_facts: true

- name: Play 2
  hosts: localhost
  gather_facts: no
  connection: local
  tasks:
    - name: Process data
      ansible.builtin.debug:
        var: data

Unfortunately, the accumulation does not work. The fact data will contain foobar only once, even for multiple hosts.


Solution

  • As a in-a-nutshell start point:

    - hosts: multiplehosts
      gather_facts: false
      
      tasks:
        - ansible.builtin.set_fact:
            some_var: "a host specific value"
    
        - ansible.builtin.debug:
            msg: "{{ ansible_play_hosts | map('extract', hostvars, 'some_var') }}"
          run_once: true