- name: Definir hostname único
  hostname:
    name: "ubuntu-{{ ansible_play_hosts.index(inventory_hostname) }}"


- name: Obter hostname real do nó
  become: true
  command: hostname
  register: node_hostname

- name: Verificar se o nó já está no cluster
  shell: |
    kubectl get nodes --no-headers | grep -w {{ node_hostname.stdout }} || echo "NOT_IN_CLUSTER"
  register: node_status
  environment:
    KUBECONFIG: /etc/kubernetes/kubelet.conf


- name: Join Kubernetes cluster
  shell: "{{ hostvars['master1']['kubeadm_join_command'] }}"
  when: 
    - hostvars['master1']['kubeadm_join_command'] is defined
    - node_status.stdout | trim == "NOT_IN_CLUSTER"


#- name: Atribuir podCIDR ao nó via hostname real
#  shell: |
#    kubectl patch node {{ node_hostname.stdout }} -p '{"spec":{"podCIDR":"192.168.2.0/24"}}'
#  when: 
#    - hostvars['master1']['kubeadm_join_command'] is defined
#    - node_status.stdout | trim == "NOT_IN_CLUSTER"