---
# etcd_ip originates from etcd_common role
- name: Check cluster status
  command: >
    etcdctl --cert {{ etcd_peer_cert_file }} --key {{ etcd_peer_key_file }} --cacert {{ etcd_peer_ca_file }} --endpoints 'https://{{ etcd_peer }}:{{ etcd_client_port }}' -w json endpoint status
  environment:
    ETCDCTL_API: 3
  register: l_etcd_cluster_status

- name: Retrieve raftIndex
  set_fact:
    etcd_member_raft_index: "{{ (l_etcd_cluster_status.stdout | from_json)[0]['Status']['raftIndex'] }}"

- block:
  # http://docs.ansible.com/ansible/playbooks_filters.html#extracting-values-from-containers
  - name: Group all raftIndices into a list
    set_fact:
      etcd_members_raft_indices: "{{ groups['oo_etcd_to_migrate'] | map('extract', hostvars, 'etcd_member_raft_index') | list | unique }}"

  - name: Check the minimum and the maximum of raftIndices is at most 1
    set_fact:
      etcd_members_raft_indices_diff: "{{ ((etcd_members_raft_indices | max | int) - (etcd_members_raft_indices | min | int)) | int }}"

  - debug:
      msg: "Raft indices difference: {{ etcd_members_raft_indices_diff }}"

  when: inventory_hostname in groups.oo_etcd_to_migrate[0]

# The cluster raft status is ok if the difference of the max and min raft index is at most 1
- name: capture the status
  set_fact:
    l_etcd_cluster_status_ok: "{{ hostvars[groups.oo_etcd_to_migrate[0]]['etcd_members_raft_indices_diff'] | int < 2 }}"
