--- # create-clones.yml - Create and configure clones from template with error handling - name: "[CLONES] Validate clone list is not empty" fail: msg: "No clones defined in 'clones' variable" when: - create_clones | default(false) - clones is not defined or clones | length == 0 - name: "[CLONES] Process each clone" block: - name: "[CLONES] Check if clone already exists" stat: path: "/etc/pve/qemu-server/{{ clone.id }}.conf" register: clone_conf changed_when: false - name: "[CLONES] Display clone status" debug: msg: "Clone {{ clone.id }} ({{ clone.hostname }}) - Status: {{ 'EXISTS' if clone_conf.stat.exists else 'WILL BE CREATED' }}" - name: "[CLONES] Clone VM from template" block: - name: "[CLONES] Execute clone command" command: > qm clone {{ vm_id }} {{ clone.id }} --name {{ clone.hostname }} --full {{ clone.full | default(0) }} register: clone_cmd when: not clone_conf.stat.exists - name: "[CLONES] Verify clone was created" stat: path: "/etc/pve/qemu-server/{{ clone.id }}.conf" register: clone_verify changed_when: false failed_when: not clone_verify.stat.exists - name: "[CLONES] Wait for clone to be ready" pause: seconds: 2 when: not clone_conf.stat.exists rescue: - name: "[CLONES] Handle clone creation error" fail: msg: | Failed to clone VM {{ vm_id }} to {{ clone.id }}: {{ ansible_failed_result | default('Unknown error') }} - name: "[CLONES] Configure Cloud-Init for clone (if needed)" block: - name: "[CLONES] Set clone hostname and IP" command: > qm set {{ clone.id }} --hostname {{ clone.hostname }} --ipconfig0 "ip={{ clone.ip }},gw={{ clone.gateway }}" register: clone_config when: not clone_conf.stat.exists - name: "[CLONES] Apply SSH keys to clone" command: > qm set {{ clone.id }} --sshkeys local:snippets/{{ vm_id }}-sshkey.pub when: not clone_conf.stat.exists rescue: - name: "[CLONES] Handle clone configuration error" debug: msg: "WARNING: Could not fully configure clone {{ clone.id }}. You may need to configure manually." - name: "[CLONES] Start clone VM" command: "qm start {{ clone.id }}" register: clone_start retries: 3 delay: 2 until: clone_start is succeeded when: not clone_conf.stat.exists - name: "[CLONES] Wait for clone to boot" pause: seconds: 3 - name: "[CLONES] Display clone creation result" debug: msg: | ✓ Clone created and started - ID: {{ clone.id }} - Hostname: {{ clone.hostname }} - IP: {{ clone.ip }} - Full clone: {{ clone.full | default(0) }} loop: "{{ clones }}" loop_control: loop_var: clone when: create_clones | default(false) - name: "[CLONES] Skip clone creation (disabled)" debug: msg: "ℹ Clone creation is disabled. Set 'create_clones: true' to enable." when: not (create_clones | default(false))