refactor ♻️: Integrate centralized helper functions for improved code consistency and idempotency across VM management tasks

This commit is contained in:
2025-11-16 08:42:26 +01:00
parent cb6a06d54f
commit 833ceb93d4
6 changed files with 380 additions and 73 deletions

View File

@@ -2,51 +2,58 @@
# create-template.yml - Convert VM to template with proper idempotency
- name: "[TEMPLATE] Check if VM is already a template"
ansible.builtin.shell: "qm config {{ vm_id }} | grep -q 'template: 1'"
register: is_template
changed_when: false
failed_when: false
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.rc == 0 else 'NOT YET A TEMPLATE' }}"
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.shell: "qm status {{ vm_id }} | grep -q 'stopped'"
register: vm_stopped
changed_when: false
failed_when: false
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 }}"
when: vm_stopped.rc != 0
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_stopped.rc != 0
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"
- 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: is_template.rc != 0
when: not is_template
changed_when: template_convert.rc == 0
- name: "[TEMPLATE] Verify conversion"
ansible.builtin.shell: "qm config {{ vm_id }} | grep 'template: 1'"
register: template_verify
changed_when: false
failed_when: template_verify.rc != 0
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:
@@ -64,4 +71,4 @@
- name: "[TEMPLATE] Skip template conversion (already done)"
ansible.builtin.debug:
msg: " VM {{ vm_id }} is already a template, skipping conversion"
when: is_template.rc == 0
when: is_template