Sometimes I need a list of hosts as a string when working with Ansible. Pacemaker clustering is one example. Here’s a snippet of Ansible that does this..

- name: Setup list of cluster hosts
      set_fact:
        host_list: "{{ host_list }}{{ (play_hosts.index(item) == 0) | ternary('',' ') }}{{ item }}"
      loop: "{{ play_hosts }}"
      run_once: yes

This play will produce the following output;

ok: [cnode1] => {
    "host_list": "cnode1 cnode2 cnode4 cnode3"
}

If you need a different separator just change the second parameter in the ternary function. The below example produces a comma-separated list of play_hosts…

- name: Setup list of cluster hosts
      set_fact:
        host_list: "{{ host_list }}{{ (play_hosts.index(item) == 0) | ternary('',',') }}{{ item }}"
      loop: "{{ play_hosts }}"
      run_once: yes
ok: [cnode1] => {
    "host_list": "cnode1,cnode2,cnode4,cnode3"
}