---
- name: Remove etcd member from cluster
  environment:
    ETCDCTL_API: "3"
    ETCDCTL_CERT: "{{ kube_cert_dir + '/etcd/server.crt' if etcd_deployment_type == 'kubeadm' else etcd_cert_dir + '/admin-' + groups['etcd'] | first + '.pem' }}"
    ETCDCTL_KEY: "{{ kube_cert_dir + '/etcd/server.key' if etcd_deployment_type == 'kubeadm' else etcd_cert_dir + '/admin-' + groups['etcd'] | first + '-key.pem' }}"
    ETCDCTL_CACERT: "{{ kube_cert_dir + '/etcd/ca.crt' if etcd_deployment_type == 'kubeadm' else etcd_cert_dir + '/ca.pem' }}"
    ETCDCTL_ENDPOINTS: "https://127.0.0.1:2379"
  delegate_to: "{{ groups['etcd'] | first }}"
  block:
  - name: Lookup members infos
    command: "{{ bin_dir }}/etcdctl member list -w json"
    register: etcd_members
    changed_when: false
    check_mode: false
    tags:
    - facts
  - name: Remove member from cluster
    command:
      argv:
      - "{{ bin_dir }}/etcdctl"
      - member
      - remove
      - "{{ '%x' | format(etcd_removed_nodes[0].ID) }}"
    vars:
      etcd_removed_nodes: "{{ (etcd_members.stdout | from_json).members | selectattr('peerURLs.0', '==', etcd_peer_url) }}"
      # This should always have at most one member, since the etcd_peer_url should be unique in the etcd cluster
    when: etcd_removed_nodes != []
    register: etcd_removal_output
    changed_when: "'Removed member' in etcd_removal_output.stdout"
