---
- name: Generate root ssh_key
  ansible.builtin.user:
    name: root
    generate_ssh_key: yes
    ssh_key_bits: 2048

- name: Fetch ssh public keys
  ansible.builtin.command:
    cmd: cat /root/.ssh/id_rsa.pub
  register: ssh_keys
  check_mode: no
  changed_when: False

- name: Print ssh public keys
  ansible.builtin.debug:
    msg: "{{ ssh_keys.stdout }}"

#- name: Autorize other kvm ssh key
#  authorized_key:
#    user: root
#    state: present
#    key: "{{ item[0] }}"
#  delegate_to: "{{ item[1] }}"
#  loop: "{{ _keys | product(_servers) | list }}"
#  vars:
#    _keys: ssh_keys.stdout
#    _servers: groups['hypervisors']
#  when: item[1] != inventory_hostname

- name: Crontab for sync libvirt xml file
  ansible.builtin.cron:
    name: "sync libvirt xml on {{ kvm_pair }}"
    state: present
    special_time: "hourly"
    user: root
    job: "if ls /etc/libvirt/qemu/*xml > /dev/null 2> /dev/null; then rsync -a --delete /etc/libvirt/qemu/*xml {{ hostvars[kvm_pair]['lan.ip'] }}:/root/libvirt-{{ inventory_hostname }}/; fi"
  when:
    - kvm_pair is defined
    - kvm_pair is not none
    - kvm_pair | length > 0
    - kvm_pair != inventory_hostname
  tags: crontab

- name: Crontab for sync list of running vm
  ansible.builtin.cron:
    name: "sync list of libvirt running vm on {{ kvm_pair }}"
    state: present
    special_time: "daily"
    user: root
    job: "virsh list --all | tee /root/virsh-list.txt | ssh {{ hostvars[kvm_pair]['lan.ip'] }} 'cat >/root/libvirt-{{ inventory_hostname }}/virsh-list.txt'"
  when:
    - kvm_pair is defined
    - kvm_pair is not none
    - kvm_pair | length > 0
    - kvm_pair != inventory_hostname
  tags: crontab
