- name: Set up the list of hosts and addresses
  set_fact:
    host_addresses: >
      {% set hosts = {} -%}
      {% for host, vars in hostvars.items() -%}
      {% set _ = hosts.update({host: vars['nodepool']['private_ipv4']}) -%}
      {% set _ = hosts.update({vars['ansible_hostname']: vars['nodepool']['private_ipv4']}) -%}
      {% endfor -%}
      {{- hosts -}}

- name: Add inventory hostnames to the hosts file
  become: yes
  lineinfile:
    dest: /etc/hosts
    state: present
    insertafter: EOF
    line: "{{ zj_host_address.value }} {{ zj_host_address.key }}"
  with_dict: "{{ host_addresses }}"
  loop_control:
    loop_var: zj_host_address