Search code examples
ansibleglusterfs

How can I build a single list from the facts collected from hosts?


I would like to have a single list, which holds all the ansible host names (which could be different from the items defined in the inventory). This list should be available for a task running on the first node only. I need this to create a GlusterFS volume. I need this list for the cluster prop of gluster.gluster.gluster_volume module.

For example check the following basic Ansible inventory file:

nodetest1-ext.somewhere.net
nodetest2-ext.somewhere.net
nodetest3-ext.somewhere.net

and playbook:

- hosts: all
  gather_facts: true

  tasks:
  - name: Print Ansible hostname of a single machine
    debug:
      msg: "{{ ansible_hostname }}" # returns stuff like: nodetest1, nodetest2, etc.

  - name: Create a list of ansible hostnames and put it into a variable
    # do some magic here
    # and prepare the single list holding the 3 items and put it to the variable:
    # ansiblehostnamelist

  - name: Print list of ansible hostname
    run_once: true  # task to run only on the first host
    debug:
      var: ansiblehostnamelist

  - name: Create Gluster Volume
    run_once: true  # task to run only on the first host
    gluster.gluster.gluster_volume:
      state: present
      name: "{{ sharedVolumeName }}"
      bricks: "{{ glusterfsBasePath }}{{ sharedVolumeOsFolder }}"
      cluster:  # <<== this is the thing where I need the list of ansible host names
                # instead of manually adding the node names:
        - nodetest1
        - nodetest2
        - nodetest3
      replicas: 3
      force: yes

Having a single list that holds all the ansible host names. This list should be available by a task running on a single machine only.


Solution

  • Based on Build a list from multiple hosts in Ansible, I was finally able to do it:

    - hosts: all
      gather_facts: true
    
      tasks:
      - name: Print all facts (just for debugging purposes)
        run_once: true  # task to run only on the first host
        debug:
          msg: "{{ ansible_play_hosts_all|map('extract', hostvars, 'ansible_hostname')|list }}"
    
      - name: Create Gluster Volume
        run_once: true  # task to run only on the first host
        gluster.gluster.gluster_volume:
          state: present
          name: "{{ sharedVolumeName }}"
          bricks: "{{ glusterfsBasePath }}{{ sharedVolumeOsFolder }}"
          cluster: "{{ ansible_play_hosts_all|map('extract', hostvars, 'ansible_hostname')|list }}"
          replicas: 3
          force: yes