- name: Clone VM from Template
  hosts: proxmox
  become: true
  vars_prompt:
    - name: "template_vmid"
      prompt: "Enter VMID for the template"
      private: no
      default: "9000"

    - name: "new_vmid"
      prompt: "Enter the new VMID"
      private: no
      default: "9001"

    - name: "new_name"
      prompt: "Enter name for the new VM"
      private: no
      default: "nixos-clone"

  vars:
    storage: "local-lvm"

  tasks:
    - name: Clone the template
      ansible.builtin.command: >
        qm clone {{ template_vmid }} {{ new_vmid }} --name {{ new_name }}

    - name: Resize disk to 10G
      ansible.builtin.command: >
        qm resize {{ new_vmid }} virtio0 +5G

    - name: Set cloud-init params
      ansible.builtin.command: >
        qm set {{ new_vmid }}
        --ciuser root
        --cipassword root
        --sshkey /root/.ssh/id_rsa.pub
        --ipconfig0 ip=dhcp

    - name: Start the new VM
      ansible.builtin.command: >
        qm start {{ new_vmid }}

    - name: Wait for QEMU Guest Agent to come online
      retries: 20
      delay: 5
      ansible.builtin.shell: |
        qm guest exec {{ new_vmid }} -- true
      register: qga_check
      until: qga_check.rc == 0

    - name: Get IP addresses via QEMU Guest Agent
      ansible.builtin.shell: |
        qm guest cmd {{ new_vmid }} network-get-interfaces
      register: qga_json
      failed_when: qga_json.rc != 0

    - name: Parse out eth0's IPv4 address
      ansible.builtin.set_fact:
        vm_ipv4: >-
          {{
            (
              qga_json.stdout
              | from_json
              | selectattr('name','equalto','eth0')
              | map(attribute='ip-addresses')
              | first
              | selectattr('ip-address-type','equalto','ipv4')
              | map(attribute='ip-address')
              | first
            )
          }}

    - name: Show the VM's IP
      ansible.builtin.debug:
        msg: "VM {{ new_vmid }} ({{ new_name }}) reports IPv4: {{ vm_ipv4 }}"

    - name: Add new VM's IP to in-memory inventory (for later tasks)
      ansible.builtin.add_host:
        name: "nixos-{{ new_vmid }}"
        ansible_host: "{{ vm_ipv4 }}"
        ansible_user: root
