---
- name: Generate root ssh_key
  user:
    name: root
    generate_ssh_key: yes
    ssh_key_bits: 2048

- name: Fetch ssh public keys
  command: cat /root/.ssh/id_rsa.pub
  register: ssh_keys
  check_mode: no
  changed_when: false

- name: Print ssh public keys
  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
  cron:
    name: "sync libvirt xml on {{ item }}"
    state: present
    special_time: "hourly"
    user: root
    job: "rsync -a --delete /etc/libvirt/qemu/ {{ hostvars[item]['ansible_hostname'] }}:/root/libvirt-{{ inventory_hostname }}/"
  loop:
    - "{{ groups['hypervisors'] }}"
  when: item != inventory_hostname

- name: Crontab for sync list of running vm
  cron:
    name: "sync list of libvirt running vm on {{ item }}"
    state: present
    special_time: "daily"
    user: root
    job: "virsh list --all | ssh {{ hostvars[item]['ansible_hostname'] }} 'cat >/root/libvirt-{{ inventory_hostname }}/virsh-list.txt'"
  loop:
    - "{{ groups['hypervisors'] }}"
  when: item != inventory_hostname
