---
- name: Clone VM from template
  community.proxmox.proxmox_kvm:
    api_host: "{{ proxmox_api_host }}"
    api_user: "{{ proxmox_api_user }}"
    api_token_id: "{{ proxmox_api_token_id }}"
    api_token_secret: "{{ proxmox_api_token_secret }}"
    node: "{{ item.value.node }}"
    clone: "debian-13-cloudinit"
    vmid: "{{ item.value.template_vmid }}"
    newid: "{{ item.value.vmid }}"
    storage: "{{ item.value.storage }}"
    name: "{{ item.key }}"
    full: yes
  loop: "{{ vms | dict2items }}"

- name: Configure VM hardware and cloud-init
  community.proxmox.proxmox_kvm:
    api_host: "{{ proxmox_api_host }}"
    api_user: "{{ proxmox_api_user }}"
    api_token_id: "{{ proxmox_api_token_id }}"
    api_token_secret: "{{ proxmox_api_token_secret }}"
    node: "{{ item.value.node }}"
    vmid: "{{ item.value.vmid }}"
    cores: "{{ item.value.cores }}"
    memory: "{{ item.value.memory }}"
    cpu: "{{ item.value.cpu_type | default('kvm64') }}"
    scsihw: virtio-scsi-pci
    net:
      net0: "virtio,bridge={{ item.value.network_bridge }}"
    ipconfig:
      ipconfig0: "ip={{ item.value.ip }}/24,gw=10.0.0.1"
    nameservers: "10.0.2.49 10.0.2.50 10.0.2.51"
    ciuser: "{{ ansible_user }}"
    sshkeys: "{{ lookup('file', '~/.ssh/id_ed25519.pub') }}"
    update: yes
  loop: "{{ vms | dict2items }}"

- name: Wait for clone to complete
  pause:
    seconds: 10

- include_tasks: disk.yml

- include_tasks: start.yml

- name: Wait for VMs to be ready
  wait_for:
    host: "{{ item.value.ip }}"
    port: 22
    delay: 10
    timeout: 300
  loop: "{{ vms | dict2items }}"
  delegate_to: localhost
