refactor ♻️: Refactored all task files to use centralized helper functions from tasks/helpers.yml, improving code consistency, maintainability, and idempotency.

All task files now use centralized helper functions, ensuring idempotency across all stages. Code is cleaner, more maintainable, and no breaking changes were introduced.
This commit is contained in:
2025-11-18 20:24:43 +01:00
parent 833ceb93d4
commit d171a4a7b9
5 changed files with 33 additions and 252 deletions

View File

@@ -20,13 +20,17 @@
- name: "[CONFIG] Import and attach disk"
block:
- name: "[CONFIG] Check if disk already exists"
ansible.builtin.stat:
path: "/var/lib/vz/images/{{ vm_id }}/vm-{{ vm_id }}-disk-0.qcow2"
register: disk_exists
changed_when: false
- name: "[CONFIG] Check if disk is already attached"
ansible.builtin.include_tasks: helpers.yml
vars:
helper_task: check_disk_attached
target_vm_id: "{{ vm_id }}"
- name: "[CONFIG] Import qcow2 disk"
- name: "[CONFIG] Display disk status"
ansible.builtin.debug:
msg: "Disk status for VM {{ vm_id }}: {{ 'ALREADY ATTACHED' if disk_attached else 'WILL BE IMPORTED & ATTACHED' }}"
- name: "[CONFIG] Import qcow2 disk (if not already attached)"
ansible.builtin.command: >
qm importdisk {{ vm_id }}
{{ debian_image_path }}
@@ -35,13 +39,13 @@
retries: "{{ max_retries }}"
delay: "{{ retry_delay }}"
until: disk_import is succeeded
when: not disk_exists.stat.exists
when: not disk_attached
- name: "[CONFIG] Verify disk import"
ansible.builtin.fail:
msg: "Disk import failed for VM {{ vm_id }}"
when:
- not disk_exists.stat.exists
- not disk_attached
- disk_import is failed
- name: "[CONFIG] Attach imported disk"
@@ -50,7 +54,7 @@
--scsihw virtio-scsi-pci
--scsi0 {{ storage }}:vm-{{ vm_id }}-disk-0
register: disk_attach
when: not disk_exists.stat.exists
when: not disk_attached
changed_when: disk_attach.rc == 0
- name: "[CONFIG] Enable serial console and set boot order"
@@ -63,7 +67,7 @@
- name: "[CONFIG] Display disk configuration"
ansible.builtin.debug:
msg: "✓ Disk configured and attached to VM {{ vm_id }}"
msg: "✓ Disk {{ 'attached' if disk_attached else 'imported and attached' }} to VM {{ vm_id }}"
rescue:
- name: "[CONFIG] Handle disk configuration error"

View File

@@ -147,3 +147,20 @@
- "/var/lib/vz/snippets/{{ target_vm_id }}-sshkey.pub"
when: helper_task == "cleanup_snippets"
##################################################################
# CHECK IF DISK IS ATTACHED
##################################################################
- name: "[HELPER] Check if disk is attached to VM"
block:
- name: "[HELPER] Query VM config for disk attachment"
ansible.builtin.shell: "qm config {{ target_vm_id }} | grep -q '^scsi0:'"
changed_when: false
failed_when: false
register: disk_check
- name: "[HELPER] Set fact: disk_attached"
ansible.builtin.set_fact:
disk_attached: "{{ disk_check.rc == 0 }}"
when: helper_task == "check_disk_attached"