75 lines
2.4 KiB
YAML
75 lines
2.4 KiB
YAML
---
|
||
# create-template.yml - Convert VM to template with proper idempotency
|
||
|
||
- name: "[TEMPLATE] Check if VM is already a template"
|
||
ansible.builtin.include_tasks: helpers.yml
|
||
vars:
|
||
helper_task: check_template
|
||
target_vm_id: "{{ vm_id }}"
|
||
|
||
- name: "[TEMPLATE] Display template status"
|
||
ansible.builtin.debug:
|
||
msg: "Template status for VM {{ vm_id }}: {{ 'ALREADY A TEMPLATE' if is_template else 'NOT YET A TEMPLATE' }}"
|
||
|
||
- name: "[TEMPLATE] Verify VM is stopped before converting"
|
||
block:
|
||
- name: "[TEMPLATE] Check VM status"
|
||
ansible.builtin.include_tasks: helpers.yml
|
||
vars:
|
||
helper_task: check_vm_status
|
||
target_vm_id: "{{ vm_id }}"
|
||
|
||
- name: "[TEMPLATE] Stop VM if running"
|
||
ansible.builtin.command: "qm stop {{ vm_id }}"
|
||
register: vm_stop
|
||
when: vm_status != 'stopped'
|
||
changed_when: vm_stop.rc == 0
|
||
|
||
- name: "[TEMPLATE] Wait for VM to stop"
|
||
ansible.builtin.pause:
|
||
seconds: 2
|
||
when: vm_status != 'stopped'
|
||
|
||
rescue:
|
||
- name: "[TEMPLATE] Handle VM stop error"
|
||
ansible.builtin.debug:
|
||
msg: "WARNING: Could not verify/stop VM {{ vm_id }}. Continuing..."
|
||
|
||
- name: "[TEMPLATE] Convert VM to template (idempotent - skipped if already template)"
|
||
block:
|
||
- name: "[TEMPLATE] Convert to template"
|
||
ansible.builtin.command: "qm template {{ vm_id }}"
|
||
register: template_convert
|
||
when: not is_template
|
||
changed_when: template_convert.rc == 0
|
||
|
||
- name: "[TEMPLATE] Verify conversion"
|
||
ansible.builtin.include_tasks: helpers.yml
|
||
vars:
|
||
helper_task: check_template
|
||
target_vm_id: "{{ vm_id }}"
|
||
|
||
- name: "[TEMPLATE] Ensure template conversion succeeded"
|
||
ansible.builtin.assert:
|
||
that:
|
||
- is_template | bool
|
||
fail_msg: "Failed to convert VM {{ vm_id }} to template"
|
||
|
||
- name: "[TEMPLATE] Display template conversion result"
|
||
ansible.builtin.debug:
|
||
msg: |
|
||
✓ VM {{ vm_id }} ({{ hostname }}) successfully converted to template
|
||
Template can now be cloned
|
||
|
||
rescue:
|
||
- name: "[TEMPLATE] Handle template conversion error"
|
||
ansible.builtin.fail:
|
||
msg: |
|
||
Failed to convert VM {{ vm_id }} to template:
|
||
{{ ansible_failed_result | default('Unknown error') }}
|
||
|
||
- name: "[TEMPLATE] Skip template conversion (already done)"
|
||
ansible.builtin.debug:
|
||
msg: "ℹ VM {{ vm_id }} is already a template, skipping conversion"
|
||
when: is_template
|