--- # create-template.yml - Convert VM to template with proper idempotency - name: "[TEMPLATE] Check if VM is already a template" shell: "qm config {{ vm_id }} | grep -q 'template: 1'" register: is_template changed_when: false failed_when: false - name: "[TEMPLATE] Display template status" debug: msg: "Template status for VM {{ vm_id }}: {{ 'ALREADY A TEMPLATE' if is_template.rc == 0 else 'NOT YET A TEMPLATE' }}" - name: "[TEMPLATE] Verify VM is stopped before converting" block: - name: "[TEMPLATE] Check VM status" shell: "qm status {{ vm_id }} | grep -q 'stopped'" register: vm_stopped changed_when: false failed_when: false - name: "[TEMPLATE] Stop VM if running" command: "qm stop {{ vm_id }}" when: vm_stopped.rc != 0 register: vm_stop - name: "[TEMPLATE] Wait for VM to stop" pause: seconds: 2 when: vm_stopped.rc != 0 rescue: - name: "[TEMPLATE] Handle VM stop error" debug: msg: "WARNING: Could not verify/stop VM {{ vm_id }}. Continuing..." - name: "[TEMPLATE] Convert VM to template" block: - name: "[TEMPLATE] Convert to template" command: "qm template {{ vm_id }}" register: template_convert when: is_template.rc != 0 changed_when: template_convert.rc == 0 - name: "[TEMPLATE] Verify conversion" shell: "qm config {{ vm_id }} | grep 'template: 1'" register: template_verify changed_when: false failed_when: template_verify.rc != 0 - name: "[TEMPLATE] Display template conversion result" debug: msg: | ✓ VM {{ vm_id }} ({{ hostname }}) successfully converted to template Template can now be cloned rescue: - name: "[TEMPLATE] Handle template conversion error" fail: msg: | Failed to convert VM {{ vm_id }} to template: {{ ansible_failed_result | default('Unknown error') }} - name: "[TEMPLATE] Skip template conversion (already done)" debug: msg: "ℹ VM {{ vm_id }} is already a template, skipping conversion" when: is_template.rc == 0