---
- name: Copy SSH public key to PVE cluster nodes
  hosts: pve_cluster
  gather_facts: yes
  tasks:
    - name: Ensure .ssh directory exists
      file:
        path: /root/.ssh
        state: directory
        mode: '0700'

    - name: Add SSH public key to authorized_keys
      authorized_key:
        user: root
        key: "{{ lookup('file', '~/.ssh/id_rsa.pub') }}"
        state: present
      ignore_errors: yes

    - name: Generate SSH key if it doesn't exist
      command: ssh-keygen -t rsa -b 4096 -f /root/.ssh/id_rsa -N ""
      when: ansible_ssh_key_add_result is failed

    - name: Add generated SSH public key to authorized_keys
      authorized_key:
        user: root
        key: "{{ lookup('file', '/root/.ssh/id_rsa.pub') }}"
        state: present
      when: ansible_ssh_key_add_result is failed

    - name: Display SSH key fingerprint
      command: ssh-keygen -lf /root/.ssh/id_rsa.pub
      register: key_fingerprint

    - name: Show key fingerprint
      debug:
        msg: "SSH Key fingerprint: {{ key_fingerprint.stdout }}"
