---
# Set 127.0.0.1 as fallback IP if we do not have host facts for host
# ansible_default_ipv4 isn't what you think.
# Thanks https://medium.com/opsops/ansible-default-ipv4-is-not-what-you-think-edb8ab154b10

- name: Gather ansible_default_ipv4 from all hosts or specific hosts
  setup:
    gather_subset: '!all,network'
    filter: "ansible_default_ipv4"
  delegate_to: "{{ item }}"
  delegate_facts: true
  when: hostvars[item].ansible_default_ipv4 is not defined
  loop: "{{ (ansible_play_hosts_all + [groups['kube_control_plane'][0]]) | unique if ansible_limit is defined else (groups['k8s_cluster'] | default([]) + groups['etcd'] | default([]) + groups['calico_rr'] | default([])) | unique }}"
  run_once: true
  ignore_unreachable: true
  tags: always

- name: Create fallback_ips_base
  set_fact:
    fallback_ips_base: |
      ---
      {% set search_hosts = (ansible_play_hosts_all + [groups['kube_control_plane'][0]]) | unique if ansible_limit is defined else (groups['k8s_cluster'] | default([]) + groups['etcd'] | default([]) + groups['calico_rr'] | default([])) | unique %}
      {% for item in search_hosts %}
      {% set found = hostvars[item].get('ansible_default_ipv4') %}
      {{ item }}: "{{ found.get('address', '127.0.0.1') }}"
      {% endfor %}
  delegate_to: localhost
  connection: local
  delegate_facts: true
  become: false
  run_once: true

- name: Set fallback_ips
  set_fact:
    fallback_ips: "{{ hostvars.localhost.fallback_ips_base | from_yaml }}"
