---
- name: remove-node | Set `nodes_to_drain` as empty list
  set_fact:
    nodes_to_drain: []

- name: remove-node | Identify nodes to drain, ignore non-cluster nodes
  shell: |
    set -o pipefail
    {{ bin_dir }}/kubectl get nodes -o json \
                  | jq .items[].metadata.name \
                  | jq "select(. | test(\"^{{ hostvars[item]['kube_override_hostname']|default(item) }}$\"))"
  loop: "{{ node.split(',') | default(groups['kube-node']) }}"
  register: nodes
  delegate_to: "{{ groups['kube-master']|first }}"
  changed_when: false
  run_once: true

- name: remove-node | Generate list of nodes to drain
  set_fact:
    nodes_to_drain: "{{  nodes_to_drain }} + [ '{{ item.stdout  | regex_replace('\"', '') }}' ]"
  loop: "{{ nodes.results }}"
  when: item.stdout | length != 0
  run_once: true

- name: remove-node | Drain node except daemonsets resource  # noqa 301
  command: >-
    {{ bin_dir }}/kubectl --kubeconfig /etc/kubernetes/admin.conf drain
      --force
      --ignore-daemonsets
      --grace-period {{ drain_grace_period }}
      --timeout {{ drain_timeout }}
      --delete-local-data {{ hostvars[item]['kube_override_hostname']|default(item) }}
  loop: "{{ nodes_to_drain }}"
  register: result
  failed_when: result.rc != 0 and not allow_ungraceful_removal
  delegate_to: "{{ groups['kube-master']|first }}"
  run_once: true
  until: result.rc == 0 or allow_ungraceful_removal
  retries: "{{ drain_retries }}"
  delay: "{{ drain_retry_delay_seconds }}"
