Ansible: reduce to the variable from registers of each host

Viewed 43
---
- hosts: all
  tasks:
  - name: Read the file
    command: cat the_file
    register: the_file

  - name: Reduce them
    set_fact:
      result: "{{ the_file.stdout }}"
      reduce: yes # magic option

When the_file in each host written as "a", "b", "c" respectively, is it possible to get the variable like ["a", "b", "c"] or "abc"?

Hosts are not connected by ssh each other, but only from the playbook running one.

1 Answers

extract the variables from the hostvars

    - set_fact:
        result: "{{ ansible_play_hosts_all|
                    map('extract', hostvars, 'the_file')|list }}"
      run_once: true

gives

result: [a, b, c]

You can join the items if you want to

    - set_fact:
        result: "{{ ansible_play_hosts_all|
                    map('extract', hostvars, 'the_file')|join }}"
      run_once: true

gives

result: abc

See Special Variables and fit the list of the hosts to your needs.

Related