From f3cab37c7ba06a15f6238b2c569cfc1280d3e384 Mon Sep 17 00:00:00 2001 From: Defame1297 Date: Sun, 29 Nov 2026 20:10:33 +0000 Subject: [PATCH] feat(pve_vm): add the pve_vm role Manage a Proxmox VE QEMU VM through the Proxmox API: clone from a template, cloud-init user, SSH keys and network, update only on detected drift, grow the boot disk, apply the power state, wait for SSH and cloud-init, and delete behind pve_vm_allow_destroy. The role never sets a cloud-init password and deletes a stored one with no_log. Inputs are validated first under the always tag: the API credentials, and pve_vm_disk_size while the disk is managed; the clone asserts pve_vm_clone_vmid. Only pve_vm_exists is public, every other fact and register is __pve_vm_. The molecule scenario runs offline on noble and resolute: validation with positive and refusal cases, drift detection over seeded VM configs, and static checks over the role's task files that no proxmox_kvm task or module_defaults entry carries cipassword and that the one task deleting a stored cipassword is no_log. The API lifecycle and the cloud-init wait are not exercised. README Roadmap: the pve_vm wave 2 line and the opnsense and proxmox_firewall line are removed; wave 3 stays. Closes #482 Assisted-by: Claude Code:claude-opus-5-5 --- README.md | 8 +- changelogs/fragments/482-pve-vm.yml | 11 + galaxy.yml | 4 +- roles/pve_vm/README.md | 133 ++++++++ roles/pve_vm/defaults/main.yml | 31 ++ roles/pve_vm/meta/argument_specs.yml | 197 +++++++++++ roles/pve_vm/meta/main.yml | 19 ++ roles/pve_vm/molecule/default/converge.yml | 30 ++ roles/pve_vm/molecule/default/molecule.yml | 107 ++++++ .../molecule/default/tasks/drift_case.yml | 24 ++ .../molecule/default/tasks/failed_run.yml | 22 ++ .../molecule/default/tasks/flatten_tasks.yml | 15 + roles/pve_vm/molecule/default/verify.yml | 323 ++++++++++++++++++ roles/pve_vm/tasks/create.yml | 29 ++ roles/pve_vm/tasks/delete.yml | 23 ++ roles/pve_vm/tasks/detect.yml | 37 ++ roles/pve_vm/tasks/detect_disk.yml | 47 +++ roles/pve_vm/tasks/detect_drift.yml | 97 ++++++ roles/pve_vm/tasks/main.yml | 90 +++++ roles/pve_vm/tasks/state.yml | 18 + roles/pve_vm/tasks/update.yml | 126 +++++++ roles/pve_vm/tasks/validate.yml | 28 ++ roles/pve_vm/tasks/wait.yml | 16 + roles/pve_vm/vars/main.yml | 4 + scripts/run_molecule_scenarios.sh | 1 + 25 files changed, 1433 insertions(+), 7 deletions(-) create mode 100644 changelogs/fragments/482-pve-vm.yml create mode 100644 roles/pve_vm/README.md create mode 100644 roles/pve_vm/defaults/main.yml create mode 100644 roles/pve_vm/meta/argument_specs.yml create mode 100644 roles/pve_vm/meta/main.yml create mode 100644 roles/pve_vm/molecule/default/converge.yml create mode 100644 roles/pve_vm/molecule/default/molecule.yml create mode 100644 roles/pve_vm/molecule/default/tasks/drift_case.yml create mode 100644 roles/pve_vm/molecule/default/tasks/failed_run.yml create mode 100644 roles/pve_vm/molecule/default/tasks/flatten_tasks.yml create mode 100644 roles/pve_vm/molecule/default/verify.yml create mode 100644 roles/pve_vm/tasks/create.yml create mode 100644 roles/pve_vm/tasks/delete.yml create mode 100644 roles/pve_vm/tasks/detect.yml create mode 100644 roles/pve_vm/tasks/detect_disk.yml create mode 100644 roles/pve_vm/tasks/detect_drift.yml create mode 100644 roles/pve_vm/tasks/main.yml create mode 100644 roles/pve_vm/tasks/state.yml create mode 100644 roles/pve_vm/tasks/update.yml create mode 100644 roles/pve_vm/tasks/validate.yml create mode 100644 roles/pve_vm/tasks/wait.yml create mode 100644 roles/pve_vm/vars/main.yml diff --git a/README.md b/README.md index 30de879..1cc89d7 100644 --- a/README.md +++ b/README.md @@ -2,10 +2,10 @@ An Ansible Collection of reusable, hardened roles for a self-hosted home lab: `cloudflared`, `docker`, `fail2ban`, `gitea`, `gitea_runner`, `network_interfaces`, -`nfs_client`, `pihole`, `pve_lxc`, `sshd`, `system_baseline`, `systemd_hardening`, `tailscale`, `traefik`, `ufw` and -`user_management`, plus the internal `_binary_update`. Roles still to come are listed under [Roadmap](#roadmap). +`nfs_client`, `pihole`, `pve_lxc`, `pve_vm`, `sshd`, `system_baseline`, `systemd_hardening`, `tailscale`, `traefik`, +`ufw` and `user_management`, plus the internal `_binary_update`. Roles still to come are listed under [Roadmap](#roadmap). -Status: roles arrive in waves. Release 3.2.0 holds the `cloudflared`, `docker`, `fail2ban`, `gitea`, `gitea_runner`, `network_interfaces`, `pihole`, `pve_lxc`, `sshd`, `system_baseline`, `systemd_hardening`, `tailscale`, `traefik`, `ufw` and `user_management` roles (and the internal `_binary_update`, which `cloudflared`, `gitea`, `gitea_runner` and `traefik` call). +Status: roles arrive in waves. Release 3.2.0 holds the `cloudflared`, `docker`, `fail2ban`, `gitea`, `gitea_runner`, `network_interfaces`, `pihole`, `pve_lxc`, `sshd`, `system_baseline`, `systemd_hardening`, `tailscale`, `traefik`, `ufw` and `user_management` roles (and the internal `_binary_update`, which `cloudflared`, `gitea`, `gitea_runner` and `traefik` call). `nfs_client` and `pve_vm` are on `main` for the next release. ## Consuming @@ -41,9 +41,7 @@ when its own prerequisites (tests, a safe cutover wherever the role already runs Still to come: -- Wave 2: `pve_vm`. - Wave 3: `rke2`, `proxmox_host`. -- Later, wave not yet assigned: `opnsense`, `proxmox_firewall`. Will not be extracted (they serve one lab or install that lab's own tool pins): `k8s_manage`, `k8s_localhost`, `k8s_lint_tools`, `minecraft_server`, `dragonwilds_server`, diff --git a/changelogs/fragments/482-pve-vm.yml b/changelogs/fragments/482-pve-vm.yml new file mode 100644 index 0000000..40e2f73 --- /dev/null +++ b/changelogs/fragments/482-pve-vm.yml @@ -0,0 +1,11 @@ +--- +minor_changes: + - >- + pve_vm - New role. Clones a Proxmox VE QEMU VM from a template through the Proxmox API (``community.proxmox``), sets + its cloud-init user, SSH keys and network, updates an existing VM only on detected drift, grows its boot disk, + applies the power state, waits for SSH and cloud-init and (with ``pve_vm_allow_destroy``) deletes it. It never sets + a cloud-init password and deletes one stored on the VM. Only ``pve_vm_exists`` is set for later plays. The input + checks run under ``tags: always``, so a tag-filtered run also needs ``pve_vm_api_user`` and + ``pve_vm_api_token_secret`` (and ``pve_vm_disk_size`` while ``pve_vm_manage_disk`` is true). Declares + Ubuntu noble and resolute guests; the molecule scenario covers the input validation and the drift detection, not + the API lifecycle. diff --git a/galaxy.yml b/galaxy.yml index f8381b4..b2562f0 100644 --- a/galaxy.yml +++ b/galaxy.yml @@ -7,7 +7,7 @@ authors: - Defame1297 description: >- Reusable, hardened Ansible roles for a self-hosted home lab (cloudflared, docker, fail2ban, - gitea, gitea_runner, network_interfaces, nfs_client, pihole, pve_lxc, sshd, system_baseline, + gitea, gitea_runner, network_interfaces, nfs_client, pihole, pve_lxc, pve_vm, sshd, system_baseline, systemd_hardening, tailscale, traefik, ufw, user_management; _binary_update is internal). license: - GPL-3.0-or-later @@ -22,7 +22,7 @@ homepage: https://git.rkdr.net/mortis/kamino issues: https://git.rkdr.net/mortis/kamino/issues # CI tests the versions pinned in requirements.yml; the lower bounds here are not tested. # No upper bound, so a consumer's newer pin does not conflict. community.general is used by system_baseline and ufw, -# ansible.posix by nfs_client, system_baseline and user_management, community.proxmox by pve_lxc (Proxmox VE guest lifecycle). +# ansible.posix by nfs_client, system_baseline and user_management, community.proxmox by pve_lxc and pve_vm (Proxmox VE guest lifecycle). # community.proxmox's modules import the Python library proxmoxer (2.3 or later) on the controller; galaxy.yml # cannot declare a Python dependency, so the README says it and requirements-dev.txt pins it for CI. dependencies: diff --git a/roles/pve_vm/README.md b/roles/pve_vm/README.md new file mode 100644 index 0000000..3de171e --- /dev/null +++ b/roles/pve_vm/README.md @@ -0,0 +1,133 @@ +# pve_vm + +Clones a Proxmox VE QEMU VM from a template through the Proxmox API and keeps its configuration, cloud-init settings, boot disk size and power state in line with the inputs. The configuration is updated only when drift is detected. Variables and their types are defined in [`meta/argument_specs.yml`](meta/argument_specs.yml), which is the source of truth. + +## Supported platforms + +Ubuntu 24.04 (noble) and 26.04 (resolute) guests, the platforms the molecule scenario runs on. The play runs for the VM's inventory host: the API calls run on the controller (`pve_vm_delegate`, default `localhost`), and only the cloud-init wait runs on the guest itself. The template the VM is cloned from must be a cloud-init image of one of these releases. + +The guest-side cloud-init wait (`cloud-init status --wait`) is untested on both releases: the test images do not ship cloud-init. + +The role targets the guests, not the Proxmox node, so it does not declare Debian trixie: the node is reached only through its API. + +## Requirements and run order + +- Use it by its fully qualified name, `mortis.kamino.pve_vm`, in a play over the VM hosts with `gather_facts: false`: the VM may not exist yet when the play starts. +- The controller needs the `community.proxmox` collection and the Python libraries `proxmoxer` 2.3 or later and `requests`. +- Role dependencies: none. +- `pve_vm_node` and `pve_vm_vmid` are required. `pve_vm_api_user` and `pve_vm_api_token_secret` have no usable default and are asserted non-empty before any change; `pve_vm_disk_size` too while `pve_vm_manage_disk` is true, unless `pve_vm_state` is `absent`. +- `pve_vm_api_host` defaults to the `ansible_host` of `pve_vm_node` from hostvars, so the node must then be an inventory host even when only the VM hosts are targeted. Set `pve_vm_api_host` explicitly when the node is not in the inventory. +- The VM's own `ansible_host` is the target of the SSH wait, and `inventory_hostname`, lowercased with underscores replaced by dashes, is its name in Proxmox. +- Run it before any role that configures the inside of the VM. Gate those on `pve_vm_exists` (below). + +### API privileges + +The API token needs, on the VM (or a pool or path above it), the template and the storage: + +- `VM.Allocate`, `VM.Clone` (on the template), `VM.Audit` and `VM.Config.*` (`VM.Config.CDROM`, `VM.Config.CPU`, `VM.Config.Cloudinit`, `VM.Config.Disk`, `VM.Config.HWType`, `VM.Config.Memory`, `VM.Config.Network`, `VM.Config.Options`), and `VM.PowerMgmt` for the power state and restarts; +- `Datastore.AllocateSpace` on the storage that holds the disks; +- `SDN.Use` on the bridge or zone when `pve_vm_network` sets a network. + +A token with privilege separation (the Proxmox default) gets the intersection of its own ACL and its user's: grant the role on both the user and the token. + +## Role variables + +| Variable | Default | Description | +|---|---|---| +| `pve_vm_node` | none (required) | Name of the Proxmox node that owns the VM. | +| `pve_vm_vmid` | none (required) | VM id; for a clone, the new id. | +| `pve_vm_state` | `present` | `present`, `started`, `stopped` or `absent`. `present` leaves the power state alone. | +| `pve_vm_allow_destroy` | `false` | Required before `absent` deletes the VM. | +| `pve_vm_clone_vmid` | none | Template id, read and asserted set only when the VM does not exist and is cloned. | +| `pve_vm_full_clone` | `true` | Full clone instead of a linked clone. | +| `pve_vm_delegate` | `localhost` | Host that runs the API module tasks. | +| `pve_vm_wait_for_guest` | `true` | Wait for SSH and cloud-init when `started`. | +| `pve_vm_agent` | `true` | QEMU guest agent. | +| `pve_vm_onboot` | `true` | Start on node boot. | +| `pve_vm_autostart` | `true` | Sent as `autostart` on update, never compared. | +| `pve_vm_memory`, `pve_vm_cores`, `pve_vm_sockets` | none | Sizing, omitted when undefined. | +| `pve_vm_network`, `pve_vm_ipconfig` | none | Mappings for `net` and `ipconfig`, see the spec. Omitted when undefined. | +| `pve_vm_nameservers` | none | List, or space or comma separated string. Omitted when undefined. | +| `pve_vm_sshkeys` | none | Cloud-init public keys, one per line. Omitted when undefined. | +| `pve_vm_ci_user` | `""` | Cloud-init user (`ciuser`). Left out of the update and of the drift check when empty. | +| `pve_vm_force_update` | `false` | Push the configuration and cloud-init settings without drift. | +| `pve_vm_manage_disk` | `true` | Grow the boot disk to `pve_vm_disk_size`. | +| `pve_vm_disk_size` | none (asserted) | Boot disk size, for example `32G`; only ever grown. | +| `pve_vm_boot_disk` | `scsi0` | Disk key whose size is read and resized. | +| `pve_vm_reboot_if_required` | `true` | Restart the VM after its boot disk was grown. | +| `pve_vm_api_user` | `""` (asserted) | API user without realm; `@` is appended. | +| `pve_vm_api_realm` | `pam` | Realm of the API user. | +| `pve_vm_api_token_id` | `-token` | API token id. | +| `pve_vm_api_token_secret` | none (asserted) | API token secret, normally vaulted. No default. `no_log`. | +| `pve_vm_api_host` | `ansible_host` of `pve_vm_node`, empty without it | Proxmox API address (port 8006). | + +The `pve_vm_api_*` inputs are applied through `module_defaults` inside the block that holds every API call of the role, and the REST lookup of the VM config sends the header `PVEAPIToken=@!=`, derived in `vars/main.yml`. + +## Variables set by the role + +- `pve_vm_exists`: the VM exists on the node. + +## Tags + +The input validation (`tasks/validate.yml`) carries `always`, so it runs whatever tags are selected. No other task is tagged, so only a play-level tag applies to them. + +## Example play + +```yaml +- name: Provision VMs + hosts: vms + gather_facts: false + roles: + - role: mortis.kamino.pve_vm + vars: + pve_vm_state: started + pve_vm_node: pve1 + pve_vm_vmid: 210 + pve_vm_clone_vmid: 9000 + pve_vm_memory: 4096 + pve_vm_cores: 2 + pve_vm_disk_size: 32G + pve_vm_network: + net0: + model: virtio + bridge: vmbr0 + tag: 20 + pve_vm_ipconfig: + ipconfig0: "ip={{ ansible_host }}/24,gw=192.0.2.1" + pve_vm_ci_user: ubuntu + pve_vm_sshkeys: "{{ lookup('ansible.builtin.file', 'files/admin.pub') }}" + pve_vm_api_user: ansible + pve_vm_api_token_secret: "{{ vault_pve_api_token_secret }}" + +- name: Configure the VMs + hosts: vms + tasks: + - name: Configure the guest + ansible.builtin.include_role: + name: mortis.kamino.user_management + when: pve_vm_exists | default(false) +``` + +## Tests + +The `default` molecule scenario runs in CI on Ubuntu 24.04 (noble) and 26.04 (resolute), the `molecule-ubuntu2404` and `molecule-ubuntu2604` images, which stand in for the guest. It runs `check` before the converge (a fresh host) and after it. The converge includes the internal task files `validate` and `detect_drift`, with a seeded VM config in Proxmox's own forms standing in for the REST lookup. + +- Positive: `validate` accepts the scenario inputs, an unmanaged disk without a size, and `absent` without a size. +- Negative: through `main`, a state outside the spec, a VM id that is not a number, a missing API user and a missing token secret; through `validate`, a missing token secret with `absent` and a managed disk without a size; through `create`, a clone without `pve_vm_clone_vmid`. Each asserts the expected message. +- Drift: `detect_drift` over seeded configs: a matching config; the cloud-init user (empty input with a different or missing live `ciuser`, a changed user, a missing `ciuser`); the SSH keys (missing, rotated, empty input); a forced update; Proxmox's other value forms; every compared dimension at once; a dropped VLAN tag. +- Static, over every task file under `tasks/` (subdirectories and nested `block`, `rescue` and `always` included): no task calling `proxmox_kvm` (as `community.proxmox.proxmox_kvm`, `community.general.proxmox_kvm`, `ansible.legacy.proxmox_kvm` or `proxmox_kvm`, by its key or through `action` or `local_action`, with its `args` merged) sends `cipassword`; no `module_defaults` entry of any task or block sets `cipassword`; exactly one such task deletes a stored `cipassword`, and it is `no_log`. + +Not exercised: the API lifecycle (lookup, clone, update, the `cipassword` delete, resize, start, stop, restart and delete), as there is no Proxmox API in the scenario; and the guest-side cloud-init wait, as the test images do not ship cloud-init. + +## Notes + +- Idempotent: yes, as far as drift detection goes, which the scenario checks: the update runs only on drift. The API calls themselves rely on `community.proxmox`, which is not tested; the update and the `cipassword` delete report changed whenever they run. +- Check mode: `--check` is the supported preview; a play-level `check_mode: true` is not supported. `proxmox_kvm` and `proxmox_disk` have no check mode support, so under `--check` the two reads (the `proxmox_kvm` `state: current` lookup and the REST GET of the VM config) run for real with `check_mode: false`, and every write is skipped and previewed instead: `Preview VM creation` for a missing VM (nothing else runs for it), `Report configuration drift` names the drifted dimensions and a pending disk resize (changed when the update or resize would run; it also reports on a real run), `Preview deletion of the stored cloud-init password` and `Preview VM power state`. Delete and restart are skipped. Roles gated on `pve_vm_exists` therefore run in check mode against existing VMs. +- Drift is checked for name, CPU type (always `host`), memory, cores, sockets, cloud-init user, `ipconfig0`, nameservers, `onboot`, agent and `net0`. A missing `ciuser` or `sshkeys` key in the live config also counts, and so does the first run after a clone. +- Cloud-init `sshkeys` are stored URL-encoded by Proxmox and cannot be diffed. A rotated `pve_vm_sshkeys` reaches an existing VM only through other detected drift, a fresh clone or `pve_vm_force_update: true`. +- The role never sets a cloud-init password (`cipassword`): the first login is by SSH key. A `cipassword` stored on a VM is deleted on the next real run, by a `no_log` task. +- Disk: the boot disk only grows. Only the digits of `pve_vm_disk_size` are compared with the current size in GB. After a resize the VM is restarted when `pve_vm_reboot_if_required` is true. +- With `pve_vm_state: absent` and `pve_vm_allow_destroy` true the VM is stopped and deleted and the play ends for that host. Without `pve_vm_allow_destroy` the role only looks the VM up and changes nothing. +- A VM that does not exist is detected by the module's "does not exist in cluster" message. Any other lookup failure stops the run, re-raised with only the module message. +- TLS certificates of the API are not verified. +- `no_log` is set on every task that carries the API token. diff --git a/roles/pve_vm/defaults/main.yml b/roles/pve_vm/defaults/main.yml new file mode 100644 index 0000000..e13c2e4 --- /dev/null +++ b/roles/pve_vm/defaults/main.yml @@ -0,0 +1,31 @@ +--- +pve_vm_state: present # present | started | stopped | absent +pve_vm_allow_destroy: false +pve_vm_full_clone: true +pve_vm_wait_for_guest: true +pve_vm_delegate: localhost +pve_vm_agent: true +pve_vm_onboot: true +# Sent on update only; Proxmox does not return it in the VM config, so it is never compared. +pve_vm_autostart: true +pve_vm_manage_disk: true +pve_vm_boot_disk: scsi0 +# Restart the VM after its boot disk was grown. +pve_vm_reboot_if_required: true +# Cloud-init (ciuser, sshkeys) is pushed to an existing VM only on other drift, on the first run +# after a clone, or when this is true: Proxmox stores sshkeys URL-encoded, so a rotated key is not +# detected as drift. +pve_vm_force_update: false + +# Cloud-init user (ciuser). Empty means not sent to Proxmox and not compared for drift. +pve_vm_ci_user: "" + +# Proxmox API credentials, asserted in tasks/validate.yml before any change. The user is the bare +# name: the role appends @. The token secret, pve_vm_api_token_secret, is a secret +# input with no default, normally vaulted. +pve_vm_api_user: "" +pve_vm_api_realm: pam +pve_vm_api_token_id: "{{ pve_vm_api_user }}-token" +# The Proxmox node's address. Guarded so the default templates to '' (and the argument validation +# passes) on a host without pve_vm_node. +pve_vm_api_host: "{{ hostvars[pve_vm_node].ansible_host if pve_vm_node is defined else '' }}" diff --git a/roles/pve_vm/meta/argument_specs.yml b/roles/pve_vm/meta/argument_specs.yml new file mode 100644 index 0000000..de29aad --- /dev/null +++ b/roles/pve_vm/meta/argument_specs.yml @@ -0,0 +1,197 @@ +--- +argument_specs: + main: + short_description: Manage a Proxmox VE QEMU VM cloned from a template + description: + - >- + Looks the VM up through the Proxmox API, deletes it when C(pve_vm_state) is absent and C(pve_vm_allow_destroy) is + true, otherwise clones it from the template C(pve_vm_clone_vmid) when it does not exist, compares the live + configuration with the desired one, updates it only on drift, grows the boot disk, applies the power state + and waits for SSH and cloud-init when the VM is started. + - >- + Every API call is delegated to C(pve_vm_delegate) (the REST lookup of the config to localhost) and authenticates + with C(pve_vm_api_user) (bare user name, C(@) is appended), C(pve_vm_api_token_id), + C(pve_vm_api_token_secret) and C(pve_vm_api_host), applied through C(module_defaults), and with the header + C(PVEAPIToken=@!=) for the REST lookup, which the role derives from them in + C(vars/main.yml) (internal, not an input). The user and the token secret have no usable default: they are + asserted non-empty in the input validation, before any change. C(community.proxmox) and, on the controller, + the Python libraries C(proxmoxer) 2.3 or later and C(requests) must be installed. TLS certificates are not + verified. + - >- + Also reads C(ansible_host) (SSH wait), C(inventory_hostname) (the VM name, lowercased with underscores replaced by + dashes) and C(ansible_check_mode). The role sets the fact C(pve_vm_exists) for later roles and plays. + - >- + Cloud-init sets C(ciuser) from C(pve_vm_ci_user); an empty user is left out of the update and not compared for + drift. The role never sets a cloud-init password (C(cipassword)) and deletes one stored on the VM on a real run. + options: + pve_vm_node: + type: str + required: true + description: + - >- + Name of the Proxmox node that owns the VM. When it is also an inventory host, its C(ansible_host) is the + default of C(pve_vm_api_host). + pve_vm_vmid: + type: int + required: true + description: + - VM id on the Proxmox node. For a clone it is the new id. + pve_vm_state: + type: str + default: present + choices: [present, started, stopped, absent] + description: + - >- + C(present) keeps the VM configured without touching its power state. C(started) and C(stopped) also apply the + power state, and C(started) additionally waits for SSH and cloud-init when C(pve_vm_wait_for_guest) is true. + C(absent) deletes the VM, but only when C(pve_vm_allow_destroy) is true. Without it the role only looks the + VM up and changes nothing, because creation, disk detection, update and power state are gated on a state + other than C(absent). + pve_vm_allow_destroy: + type: bool + default: false + description: + - Safety switch required before C(pve_vm_state=absent) deletes the VM. + pve_vm_clone_vmid: + type: raw + description: + - >- + Template VM id to clone. Only read when the VM does not exist and the play is not in check mode. The type is + not fixed, so it can be given as a Jinja expression that resolves to the id. + pve_vm_full_clone: + type: bool + default: true + description: + - Full clone instead of a linked clone. + pve_vm_delegate: + type: str + default: localhost + description: + - Host that executes the Proxmox API module tasks. The REST lookup of the VM config always runs on localhost. + pve_vm_wait_for_guest: + type: bool + default: true + description: + - >- + When true and C(pve_vm_state) is started, wait for SSH on port 22 of C(ansible_host) and then for + C(cloud-init status --wait) on the guest. + pve_vm_agent: + type: bool + default: true + description: + - Enable the QEMU guest agent. Compared with the live config for drift. + pve_vm_onboot: + type: bool + default: true + description: + - Start the VM when the node boots. Compared with the live config for drift. + pve_vm_autostart: + type: bool + default: true + description: + - >- + Passed to the module as C(autostart) on update. Not compared for drift, because Proxmox does not return it in + the VM config. + pve_vm_memory: + type: raw + description: + - Memory in MB. Omitted from the update when undefined. Compared as an integer for drift. + pve_vm_cores: + type: raw + description: + - CPU cores. Omitted from the update when undefined. Compared as an integer for drift. + pve_vm_sockets: + type: raw + description: + - CPU sockets. Omitted from the update when undefined. Compared as an integer for drift. + pve_vm_network: + type: raw + description: + - >- + Mapping passed to the module as C(net), for example C(net0) with C(model), C(bridge), C(tag) and C(firewall). + Omitted when undefined. Only C(net0) is compared for drift. + pve_vm_ipconfig: + type: raw + description: + - >- + Mapping passed to the module as C(ipconfig), for example C(ipconfig0) with a string such as + C(ip=
/24,gw=). Omitted when undefined. Only C(ipconfig0) is compared for drift, token order + ignored. + pve_vm_nameservers: + type: raw + description: + - Nameservers as a list, or a space or comma separated string. Omitted when undefined. + pve_vm_sshkeys: + type: str + description: + - >- + Public keys written to the cloud-init C(sshkeys) field, one per line. Omitted when undefined. Proxmox stores + them URL-encoded, so a change is not detected as drift and is only applied on a fresh clone, on other drift + or with C(pve_vm_force_update). + pve_vm_ci_user: + type: str + default: "" + description: + - >- + Cloud-init user (C(ciuser)). Left out of the update and not compared for drift when empty. Compared with the + live C(ciuser) otherwise. + pve_vm_force_update: + type: bool + default: false + description: + - Push cloud-init settings (user, sshkeys) and the whole configuration even without detected drift. + pve_vm_manage_disk: + type: bool + default: true + description: + - >- + Grow the boot disk to C(pve_vm_disk_size). While true, C(pve_vm_disk_size) must be set; the input validation + asserts it unless C(pve_vm_state) is absent. + pve_vm_disk_size: + type: raw + description: + - >- + Desired boot disk size, for example C(32G). Only the digits are compared with the current size in GB, and the + disk is only ever grown. + pve_vm_boot_disk: + type: str + default: scsi0 + description: + - Disk key whose size is read and resized. + pve_vm_reboot_if_required: + type: bool + default: true + description: + - Restart the VM after its boot disk was grown. + pve_vm_api_user: + type: str + default: "" + description: + - >- + Proxmox API user, the bare name without realm (C(@) is appended). Required: the role + asserts it is non-empty before any change. + pve_vm_api_realm: + type: str + default: pam + description: + - Authentication realm of C(pve_vm_api_user), appended as C(@) in C(module_defaults) and in the REST header. + pve_vm_api_token_id: + type: str + description: + - >- + API token id, without the user part. Role default C(-token), a Jinja expression in + C(defaults/main.yml), so it is not repeated here. + pve_vm_api_token_secret: + type: str + no_log: true + description: + - >- + API token secret, normally vaulted. No default. Required: the role asserts it is set and non-empty before + any change. Every task that carries it is C(no_log). + pve_vm_api_host: + type: str + description: + - >- + Address of the Proxmox API (port 8006). Role default the C(ansible_host) of C(pve_vm_node) from hostvars, or + empty when C(pve_vm_node) is undefined; a Jinja expression in C(defaults/main.yml), so it is not repeated + here. Set it explicitly when the node is not an inventory host. diff --git a/roles/pve_vm/meta/main.yml b/roles/pve_vm/meta/main.yml new file mode 100644 index 0000000..48787ff --- /dev/null +++ b/roles/pve_vm/meta/main.yml @@ -0,0 +1,19 @@ +--- +galaxy_info: + role_name: pve_vm + namespace: mortis + author: Defame1297 + license: GPL-3.0-or-later + description: Clone, configure, resize, start, stop and delete Proxmox VE QEMU VMs through the Proxmox API, with cloud-init settings and drift detection. + min_ansible_version: "2.22" + platforms: + - name: Ubuntu + versions: + - noble + - resolute + galaxy_tags: + - proxmox + - vm + - cloudinit + - provisioning +dependencies: [] diff --git a/roles/pve_vm/molecule/default/converge.yml b/roles/pve_vm/molecule/default/converge.yml new file mode 100644 index 0000000..e6ca652 --- /dev/null +++ b/roles/pve_vm/molecule/default/converge.yml @@ -0,0 +1,30 @@ +--- +# The validation and the drift detection only: main.yml would also call the Proxmox API to look +# the VM up and fetch its config, which the scenario does not exercise (README, Tests). The fetched +# config is seeded instead, as the fact detect_disk.yml sets from the REST lookup. +- name: Converge + hosts: all + gather_facts: false + tasks: + - name: Validate the inputs + ansible.builtin.include_role: + name: mortis.kamino.pve_vm + tasks_from: validate + vars: + pve_vm_disk_size: 32G + + - name: Seed the live VM config the REST lookup would return + ansible.builtin.set_fact: + __pve_vm_config: "{{ pve_vm_test_config }}" + + - name: Detect configuration drift + ansible.builtin.include_role: + name: mortis.kamino.pve_vm + tasks_from: detect_drift + + - name: Assert the seeded config matches the inputs + ansible.builtin.assert: + that: + - not (__pve_vm_needs_update | bool) + fail_msg: The seeded config, which matches every input, was reported as drift + quiet: true diff --git a/roles/pve_vm/molecule/default/molecule.yml b/roles/pve_vm/molecule/default/molecule.yml new file mode 100644 index 0000000..8bf745e --- /dev/null +++ b/roles/pve_vm/molecule/default/molecule.yml @@ -0,0 +1,107 @@ +--- +# Runs on the repository's own runner (label kamino-molecule), in the molecule-ubuntu2404 +# (MOLECULE_IMAGE) and molecule-ubuntu2604 (MOLECULE_IMAGE_2604) images, pinned in +# .gitea/workflows/molecule.yml. The containers stand in for the guest: the role's input +# validation and its drift detection over a seeded VM config run against them. Nothing calls the +# Proxmox API (README, Tests). The containers run systemd as PID 1 with a writable cgroup; no +# privileged mode. +driver: + name: docker +platforms: + - name: ${KAMINO_RUN_ID:-local}-pve-vm-instance + labels: + net.rkdr.mortis.molecule-run: "${KAMINO_RUN_ID:-local}" + image: ${MOLECULE_IMAGE} + pre_build_image: true + pull: true + command: /sbin/init + cgroupns_mode: host + volumes: + - /sys/fs/cgroup:/sys/fs/cgroup:rw + tmpfs: + - /run + - /run/lock + security_opts: + - apparmor=unconfined + - name: ${KAMINO_RUN_ID:-local}-pve-vm-2604-instance + labels: + net.rkdr.mortis.molecule-run: "${KAMINO_RUN_ID:-local}" + image: ${MOLECULE_IMAGE_2604} + pre_build_image: true + pull: true + command: /sbin/init + cgroupns_mode: host + volumes: + - /sys/fs/cgroup:/sys/fs/cgroup:rw + tmpfs: + - /run + - /run/lock + security_opts: + - apparmor=unconfined +provisioner: + name: ansible + # One source for every play, so the converge, the drift cases and the negative tests in + # verify.yml start from the same valid input, which matches the seeded VM config of converge.yml. + inventory: + group_vars: + all: + pve_vm_node: pve-node + pve_vm_vmid: 9200 + # The node is not an inventory host, from which the role defaults the API address; + # argument validation templates that default, so main would fail on it instead. + pve_vm_api_host: 192.0.2.1 + pve_vm_api_user: molecule + pve_vm_api_token_secret: not-a-secret + # pve_vm_disk_size is set where a case needs it, so the refusal case can leave it undefined. + pve_vm_state: started + pve_vm_memory: 2048 + pve_vm_cores: 2 + pve_vm_sockets: 1 + pve_vm_ci_user: ubuntu + pve_vm_sshkeys: ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIMoleculeTestKeyNotARealKey molecule + pve_vm_network: + net0: + model: virtio + bridge: vmbr0 + tag: 20 + firewall: true + pve_vm_ipconfig: + ipconfig0: ip=192.0.2.30/24,gw=192.0.2.1 + pve_vm_nameservers: + - 192.0.2.53 + - 198.51.100.53 + # The live config the REST lookup would return, in Proxmox's own forms: agent with flags, + # ipconfig0 tokens reordered, sshkeys URL-encoded, nameservers space-separated. + pve_vm_test_config: + name: "{{ inventory_hostname | lower | replace('_', '-') }}" + cpu: host + memory: 2048 + cores: 2 + sockets: 1 + ciuser: ubuntu + sshkeys: ssh-ed25519%20AAAAC3NzaC1lZDI1NTE5AAAAIMoleculeTestKeyNotARealKey%20molecule%0A + ipconfig0: gw=192.0.2.1,ip=192.0.2.30/24 + nameserver: 192.0.2.53 198.51.100.53 + onboot: 1 + agent: fstrim_cloned_disks=1,enabled=1 + net0: virtio=BC:24:11:00:00:01,bridge=vmbr0,firewall=1,tag=20 + scsi0: local-lvm:vm-9200-disk-0,size=32G +verifier: + name: ansible +scenario: + # molecule's default sequence minus both destroys (scripts/run_molecule_scenarios.sh removes the + # containers as soon as this scenario ends; after a local run, run `molecule destroy` yourself), + # plus a check before the converge (fresh host) and one after it (converged host). + test_sequence: + - dependency + - cleanup + - syntax + - create + - prepare + - check + - converge + - check + - idempotence + - side_effect + - verify + - cleanup diff --git a/roles/pve_vm/molecule/default/tasks/drift_case.yml b/roles/pve_vm/molecule/default/tasks/drift_case.yml new file mode 100644 index 0000000..c174d3a --- /dev/null +++ b/roles/pve_vm/molecule/default/tasks/drift_case.yml @@ -0,0 +1,24 @@ +--- +# One drift case: seeds the live VM config the REST lookup would return, runs the role's drift +# detection with the inputs the caller sets on the include, and asserts each expected drift fact. +# Input: pve_vm_test_case (name, config, expect: a mapping of drift dimension to true or false, +# needs_update for the combined result). +- name: "Seed the live VM config, case {{ pve_vm_test_case.name }}" + ansible.builtin.set_fact: + __pve_vm_config: "{{ pve_vm_test_case.config }}" + +- name: "Detect configuration drift, case {{ pve_vm_test_case.name }}" + ansible.builtin.include_role: + name: mortis.kamino.pve_vm + tasks_from: detect_drift + +- name: "Assert the drift facts, case {{ pve_vm_test_case.name }}" + ansible.builtin.assert: + that: (lookup('ansible.builtin.vars', pve_vm_test_fact) | bool) == (item.value | bool) + fail_msg: "{{ pve_vm_test_fact }} is {{ lookup('ansible.builtin.vars', pve_vm_test_fact) }}, expected {{ item.value }}" + quiet: true + vars: + pve_vm_test_fact: "{{ '__pve_vm_needs_update' if item.key == 'needs_update' else '__pve_vm_drift_' ~ item.key }}" + loop: "{{ pve_vm_test_case.expect | dict2items }}" + loop_control: + label: "{{ item.key }}" diff --git a/roles/pve_vm/molecule/default/tasks/failed_run.yml b/roles/pve_vm/molecule/default/tasks/failed_run.yml new file mode 100644 index 0000000..83e481e --- /dev/null +++ b/roles/pve_vm/molecule/default/tasks/failed_run.yml @@ -0,0 +1,22 @@ +--- +# One failing run: includes the role's task file named by the case, with the inputs the caller +# sets on the include, and asserts that the expected message, not something else, stopped it. +# Input: pve_vm_test_case (name, tasks_from, expect). +- name: "Run the role, case {{ pve_vm_test_case.name }}" + block: + - name: "Include the role, case {{ pve_vm_test_case.name }}" + ansible.builtin.include_role: + name: mortis.kamino.pve_vm + tasks_from: "{{ pve_vm_test_case.tasks_from }}" + + # Only reached when the include returned. The message must not contain the expected + # text, so the rescue below cannot mistake it for the failure under test. + - name: "Fail because the include returned, case {{ pve_vm_test_case.name }}" + ansible.builtin.fail: + msg: The role accepted the input + rescue: + - name: "The expected failure stopped the run, case {{ pve_vm_test_case.name }}" + ansible.builtin.assert: + that: pve_vm_test_case.expect in (ansible_failed_result.msg | default('')) + fail_msg: "Expected '{{ pve_vm_test_case.expect }}', got: {{ ansible_failed_result.msg | default('') }}" + quiet: true diff --git a/roles/pve_vm/molecule/default/tasks/flatten_tasks.yml b/roles/pve_vm/molecule/default/tasks/flatten_tasks.yml new file mode 100644 index 0000000..8b732c1 --- /dev/null +++ b/roles/pve_vm/molecule/default/tasks/flatten_tasks.yml @@ -0,0 +1,15 @@ +--- +# One level of the static check's flattening: moves the pending tasks into pve_vm_test_tasks and +# makes their block, rescue and always lists the next pending ones, then recurses until none is left. +# Both facts are templated from the values before this task. +- name: Flatten one level of blocks + ansible.builtin.set_fact: + pve_vm_test_tasks: "{{ [pve_vm_test_tasks, pve_vm_test_pending] | flatten(levels=1) }}" + pve_vm_test_pending: >- + {{ [pve_vm_test_pending | map(attribute='block', default=[]) | list, + pve_vm_test_pending | map(attribute='rescue', default=[]) | list, + pve_vm_test_pending | map(attribute='always', default=[]) | list] | flatten(levels=2) }} + +- name: Flatten the next level + ansible.builtin.include_tasks: flatten_tasks.yml + when: pve_vm_test_pending | length > 0 diff --git a/roles/pve_vm/molecule/default/verify.yml b/roles/pve_vm/molecule/default/verify.yml new file mode 100644 index 0000000..e44bc17 --- /dev/null +++ b/roles/pve_vm/molecule/default/verify.yml @@ -0,0 +1,323 @@ +--- +# The refusal cases run first: each fails in the input validation, before any API call. +- name: Refuse invalid input + hosts: all + gather_facts: false + tasks: + - name: Refuse a state outside the argument spec choices + ansible.builtin.include_tasks: tasks/failed_run.yml + vars: + pve_vm_state: running + pve_vm_test_case: + name: state-choice + tasks_from: main + expect: pve_vm_state must be one of + + - name: Refuse a run without an API user + ansible.builtin.include_tasks: tasks/failed_run.yml + vars: + pve_vm_api_user: "" + pve_vm_test_case: + name: no-api-user + tasks_from: main + expect: The Proxmox API calls need pve_vm_api_user + + - name: Refuse a run without an API token secret + ansible.builtin.include_tasks: tasks/failed_run.yml + vars: + pve_vm_api_token_secret: "" + pve_vm_test_case: + name: no-token-secret + tasks_from: main + expect: The Proxmox API calls need pve_vm_api_user + + - name: Refuse a deletion without an API token secret + ansible.builtin.include_tasks: tasks/failed_run.yml + vars: + pve_vm_state: absent + pve_vm_api_token_secret: "" + pve_vm_test_case: + name: absent-no-token-secret + tasks_from: validate + expect: The Proxmox API calls need pve_vm_api_user + + - name: Refuse a managed disk without a size + ansible.builtin.include_tasks: tasks/failed_run.yml + vars: + pve_vm_test_case: + name: no-disk-size + tasks_from: validate + expect: pve_vm_disk_size (for example 32G) must be set + + - name: Refuse a VM id that is not a number + ansible.builtin.include_tasks: tasks/failed_run.yml + vars: + pve_vm_vmid: not-a-number + pve_vm_test_case: + name: vmid-type + tasks_from: main + expect: pve_vm_vmid + + # create.yml is reached only after the API lookup found no VM; its assert precedes the clone. + - name: Refuse a clone without a template id + ansible.builtin.include_tasks: tasks/failed_run.yml + vars: + pve_vm_test_case: + name: no-clone-vmid + tasks_from: create + expect: which needs pve_vm_clone_vmid + +- name: Accept valid input + hosts: all + gather_facts: false + tasks: + - name: Accept an unmanaged disk without a size + ansible.builtin.include_role: + name: mortis.kamino.pve_vm + tasks_from: validate + vars: + pve_vm_manage_disk: false + + - name: Accept a deletion without a disk size + ansible.builtin.include_role: + name: mortis.kamino.pve_vm + tasks_from: validate + vars: + pve_vm_state: absent + +- name: Detect drift on a seeded VM config + hosts: all + gather_facts: false + vars: + pve_vm_test_no_drift: + forced: false + missing_keys: false + name: false + cpu: false + resources: false + ciuser: false + ipconfig: false + nameservers: false + onboot: false + agent: false + network: false + needs_update: false + tasks: + - name: Report no drift when the live config matches + ansible.builtin.include_tasks: tasks/drift_case.yml + vars: + pve_vm_test_case: + name: match + config: "{{ pve_vm_test_config }}" + expect: "{{ pve_vm_test_no_drift }}" + + - name: Ignore the live ciuser while pve_vm_ci_user is empty + ansible.builtin.include_tasks: tasks/drift_case.yml + vars: + pve_vm_ci_user: "" + pve_vm_test_case: + name: ciuser-empty + config: "{{ pve_vm_test_config | combine({'ciuser': 'someone-else'}) }}" + expect: "{{ pve_vm_test_no_drift }}" + + - name: Ignore a missing live ciuser while pve_vm_ci_user is empty + ansible.builtin.include_tasks: tasks/drift_case.yml + vars: + pve_vm_ci_user: "" + pve_vm_test_case: + name: ciuser-empty-unset + config: "{{ pve_vm_test_config | dict2items | rejectattr('key', 'eq', 'ciuser') | items2dict }}" + expect: "{{ pve_vm_test_no_drift }}" + + - name: Report a live ciuser other than pve_vm_ci_user + ansible.builtin.include_tasks: tasks/drift_case.yml + vars: + pve_vm_ci_user: admin + pve_vm_test_case: + name: ciuser-changed + config: "{{ pve_vm_test_config }}" + expect: "{{ pve_vm_test_no_drift | combine({'ciuser': true, 'needs_update': true}) }}" + + - name: Report a live config without ciuser + ansible.builtin.include_tasks: tasks/drift_case.yml + vars: + pve_vm_test_case: + name: ciuser-missing + config: "{{ pve_vm_test_config | dict2items | rejectattr('key', 'eq', 'ciuser') | items2dict }}" + expect: "{{ pve_vm_test_no_drift | combine({'missing_keys': true, 'ciuser': true, 'needs_update': true}) }}" + + - name: Report a live config without sshkeys + ansible.builtin.include_tasks: tasks/drift_case.yml + vars: + pve_vm_test_case: + name: sshkeys-missing + config: "{{ pve_vm_test_config | dict2items | rejectattr('key', 'eq', 'sshkeys') | items2dict }}" + expect: "{{ pve_vm_test_no_drift | combine({'missing_keys': true, 'needs_update': true}) }}" + + # Proxmox stores sshkeys URL-encoded, so a rotated key is not drift; pve_vm_force_update pushes it. + - name: Report no drift for rotated sshkeys + ansible.builtin.include_tasks: tasks/drift_case.yml + vars: + pve_vm_sshkeys: ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIRotatedTestKeyNotARealKey molecule + pve_vm_test_case: + name: sshkeys-rotated + config: "{{ pve_vm_test_config }}" + expect: "{{ pve_vm_test_no_drift }}" + + - name: Expect no sshkeys in the live config while pve_vm_sshkeys is empty + ansible.builtin.include_tasks: tasks/drift_case.yml + vars: + pve_vm_sshkeys: "" + pve_vm_test_case: + name: sshkeys-empty + config: "{{ pve_vm_test_config | dict2items | rejectattr('key', 'eq', 'sshkeys') | items2dict }}" + expect: "{{ pve_vm_test_no_drift }}" + + - name: Report forced drift with pve_vm_force_update + ansible.builtin.include_tasks: tasks/drift_case.yml + vars: + pve_vm_force_update: true + pve_vm_test_case: + name: forced + config: "{{ pve_vm_test_config }}" + expect: "{{ pve_vm_test_no_drift | combine({'forced': true, 'needs_update': true}) }}" + + - name: Read Proxmox's other forms as no drift + ansible.builtin.include_tasks: tasks/drift_case.yml + vars: + pve_vm_nameservers: 192.0.2.53,198.51.100.53 + pve_vm_test_case: + name: other-forms + config: "{{ pve_vm_test_config | combine({'cpu': 'cputype=host,flags=+aes', 'agent': '1'}) }}" + expect: "{{ pve_vm_test_no_drift }}" + + - name: Report drift in each compared dimension + ansible.builtin.include_tasks: tasks/drift_case.yml + vars: + pve_vm_test_case: + name: all-dimensions + config: >- + {{ pve_vm_test_config | combine({'name': 'other-name', 'cpu': 'kvm64', 'memory': 1024, + 'ipconfig0': 'ip=192.0.2.31/24,gw=192.0.2.1', 'nameserver': '192.0.2.53', 'onboot': 0, + 'agent': 'enabled=0', 'net0': 'virtio=BC:24:11:00:00:01,bridge=vmbr1,tag=20'}) }} + expect: + forced: false + missing_keys: false + name: true + cpu: true + resources: true + ciuser: false + ipconfig: true + nameservers: true + onboot: true + agent: true + network: true + needs_update: true + + - name: Report a live VLAN tag that the inputs drop + ansible.builtin.include_tasks: tasks/drift_case.yml + vars: + pve_vm_network: + net0: + model: virtio + bridge: vmbr0 + firewall: true + pve_vm_test_case: + name: tag-dropped + config: "{{ pve_vm_test_config }}" + expect: "{{ pve_vm_test_no_drift | combine({'network': true, 'needs_update': true}) }}" + +# Static: the role must never send a cloud-init password, and its delete of a stored one must not +# log the task, so these read the role's own task files on the controller. +- name: Verify the role's cloud-init password handling + hosts: localhost + gather_facts: false + vars: + pve_vm_test_task_dir: "{{ (playbook_dir ~ '/../../tasks') | realpath }}" + # Every name a task can call the module by. + pve_vm_test_kvm_names: + - community.proxmox.proxmox_kvm + - community.general.proxmox_kvm + - ansible.legacy.proxmox_kvm + - proxmox_kvm + tasks: + - name: Find the role's task files, subdirectories included + ansible.builtin.find: + paths: "{{ pve_vm_test_task_dir }}" + patterns: ["*.yml", "*.yaml"] + recurse: true + register: pve_vm_test_files + + - name: Read the role's task files + ansible.builtin.set_fact: + pve_vm_test_pending: >- + {{ [pve_vm_test_pending | default([]), + lookup('ansible.builtin.file', item) | from_yaml] | flatten(levels=1) }} + loop: "{{ pve_vm_test_files.files | map(attribute='path') | sort }}" + + - name: Start the flattened task list + ansible.builtin.set_fact: + pve_vm_test_tasks: [] + + # Recurses through block, rescue and always to any depth. + - name: Flatten the blocks + ansible.builtin.include_tasks: tasks/flatten_tasks.yml + + # A task calls the module by its key, or through action or local_action, either a mapping + # with module or a string that starts with the module name. Its args are merged in. + - name: Summarise each proxmox_kvm task + ansible.builtin.set_fact: + pve_vm_test_kvm: >- + {{ pve_vm_test_kvm | default([]) + [{ + 'name': item.name | default('(unnamed)'), + 'sends': ('cipassword' in pve_vm_test_args) + or (pve_vm_test_raw is string and 'cipassword=' in pve_vm_test_raw), + 'deletes': ('cipassword' in (pve_vm_test_args.delete | default('') | string).split(',')) + or (pve_vm_test_raw is string and pve_vm_test_raw is search('delete=\\S*cipassword')), + 'no_log': item.no_log | default(false) | bool, + }] }} + vars: + pve_vm_test_key: "{{ pve_vm_test_kvm_names | select('in', item) | first | default('') }}" + pve_vm_test_action: "{{ item.action | default(item.local_action | default('')) }}" + pve_vm_test_action_kvm: >- + {{ (pve_vm_test_action is mapping and pve_vm_test_action.module | default('') in pve_vm_test_kvm_names) + or (pve_vm_test_action is string and (pve_vm_test_action.split() | first | default('')) in pve_vm_test_kvm_names) }} + pve_vm_test_raw: >- + {{ item[pve_vm_test_key] if pve_vm_test_key + else (pve_vm_test_action | dict2items | rejectattr('key', 'eq', 'module') | items2dict + if pve_vm_test_action is mapping else pve_vm_test_action) }} + pve_vm_test_args: >- + {{ (pve_vm_test_raw if pve_vm_test_raw is mapping else {}) | combine(item.args | default({})) }} + loop: "{{ pve_vm_test_tasks }}" + loop_control: + label: "{{ item.name | default('(unnamed)') }}" + when: pve_vm_test_key | length > 0 or pve_vm_test_action_kvm | bool + + - name: Assert no proxmox_kvm task sends cipassword + ansible.builtin.assert: + that: + - pve_vm_test_kvm | default([]) | length > 0 + - pve_vm_test_kvm | selectattr('sends') | list | length == 0 + fail_msg: "proxmox_kvm tasks sending cipassword: {{ pve_vm_test_kvm | default([]) | selectattr('sends') | map(attribute='name') | list }}" + quiet: true + + # Any module, any spelling or group: no default the role sets may carry cipassword. + - name: Assert no module_defaults sets cipassword + ansible.builtin.assert: + that: + - >- + [item.module_defaults] | flatten(levels=1) | map('dict2items') | flatten(levels=1) + | map(attribute='value') | select('contains', 'cipassword') | list | length == 0 + fail_msg: "module_defaults with cipassword on '{{ item.name | default('(unnamed)') }}'" + quiet: true + loop: "{{ pve_vm_test_tasks | selectattr('module_defaults', 'defined') | list }}" + loop_control: + label: "{{ item.name | default('(unnamed)') }}" + + - name: Assert the stored cipassword is deleted by one no_log task + ansible.builtin.assert: + that: + - pve_vm_test_kvm | selectattr('deletes') | list | length == 1 + - pve_vm_test_kvm | selectattr('deletes') | selectattr('no_log') | list | length == 1 + fail_msg: "Tasks deleting cipassword: {{ pve_vm_test_kvm | selectattr('deletes') | list }}" + quiet: true diff --git a/roles/pve_vm/tasks/create.yml b/roles/pve_vm/tasks/create.yml new file mode 100644 index 0000000..a8a3815 --- /dev/null +++ b/roles/pve_vm/tasks/create.yml @@ -0,0 +1,29 @@ +--- +# Here, not in validate.yml: whether a clone happens is known only after the API lookup. +- name: Assert the template to clone is set + ansible.builtin.assert: + that: + - pve_vm_clone_vmid is defined + fail_msg: >- + VM {{ pve_vm_vmid }} does not exist on {{ pve_vm_node }}, so it is cloned, which needs + pve_vm_clone_vmid, the VM id of the template. Set it, or create the VM by other means. + quiet: true + +- name: Clone VM from template + no_log: true # carries the API token secret + delegate_to: "{{ pve_vm_delegate }}" + community.proxmox.proxmox_kvm: + node: "{{ pve_vm_node }}" + clone: template + vmid: "{{ pve_vm_clone_vmid }}" + newid: "{{ pve_vm_vmid }}" + name: "{{ inventory_hostname | lower | replace('_', '-') }}" + full: "{{ pve_vm_full_clone }}" + timeout: 600 + state: present + register: __pve_vm_clone + +- name: Record that the VM was just cloned + ansible.builtin.set_fact: + # Forces one cloud-init update (ciuser, sshkeys) in update.yml. + __pve_vm_created: "{{ __pve_vm_clone is changed }}" diff --git a/roles/pve_vm/tasks/delete.yml b/roles/pve_vm/tasks/delete.yml new file mode 100644 index 0000000..a2a571e --- /dev/null +++ b/roles/pve_vm/tasks/delete.yml @@ -0,0 +1,23 @@ +--- +- name: Stop VM before deletion (if running) + no_log: true # defence in depth: the module already masks the API token secret + delegate_to: "{{ pve_vm_delegate }}" + community.proxmox.proxmox_kvm: + node: "{{ pve_vm_node }}" + vmid: "{{ pve_vm_vmid }}" + state: stopped + when: + - pve_vm_exists + - not ansible_check_mode + +- name: Delete VM + no_log: true # defence in depth: the module already masks the API token secret + delegate_to: "{{ pve_vm_delegate }}" + community.proxmox.proxmox_kvm: + node: "{{ pve_vm_node }}" + vmid: "{{ pve_vm_vmid }}" + state: absent + when: + - pve_vm_exists + - not ansible_check_mode + register: __pve_vm_delete diff --git a/roles/pve_vm/tasks/detect.yml b/roles/pve_vm/tasks/detect.yml new file mode 100644 index 0000000..989dd26 --- /dev/null +++ b/roles/pve_vm/tasks/detect.yml @@ -0,0 +1,37 @@ +--- +# no_log hides the whole failure of the lookup below, so the operator would only see "output hidden +# due to no_log". The rescue re-raises just the module's msg, which is safe to show: the module +# masks the token secret in everything it returns (its invocation echo is not used here). +- name: Look up the VM + block: + - name: Check if VM exists + no_log: true # defence in depth: the module already masks the API token secret + delegate_to: "{{ pve_vm_delegate }}" + community.proxmox.proxmox_kvm: + node: "{{ pve_vm_node }}" + vmid: "{{ pve_vm_vmid }}" + state: current + register: __pve_vm_info + # proxmox_kvm declares no check mode support, so --check would skip this lookup, leave + # pve_vm_exists false and skip everything after it. state=current only reads (GET of the VM + # and its status), so it runs for real under --check as well. + check_mode: false + # An absent VM is an expected answer here: for state=current the module fails with + # "VM with vmid does not exist in cluster". Any other failure (API, auth, network) is + # real and must stop the run instead of being read as "VM absent", which would send + # create.yml after an existing VM. + failed_when: + - __pve_vm_info.failed | default(false) + - "'does not exist in cluster' not in (__pve_vm_info.msg | default(''))" + changed_when: false + rescue: + - name: Fail with the module message + ansible.builtin.fail: + msg: >- + Looking up VM {{ pve_vm_vmid }} on {{ pve_vm_node }} failed: + {{ ansible_failed_result.msg | default('no message') }} + +- name: Set VM existence fact + ansible.builtin.set_fact: + pve_vm_exists: >- + {{ __pve_vm_info.vmid is defined or __pve_vm_info.status is defined }} diff --git a/roles/pve_vm/tasks/detect_disk.yml b/roles/pve_vm/tasks/detect_disk.yml new file mode 100644 index 0000000..5ca6b2e --- /dev/null +++ b/roles/pve_vm/tasks/detect_disk.yml @@ -0,0 +1,47 @@ +--- +- name: Get current VM config via REST API + no_log: true # Authorization header carries the API token + delegate_to: localhost + ansible.builtin.uri: + url: "https://{{ pve_vm_api_host }}:8006/api2/json/nodes/{{ pve_vm_node }}/qemu/{{ pve_vm_vmid }}/config" + method: GET + headers: + Authorization: "{{ __pve_vm_api_auth_header }}" + register: __pve_vm_current_config + # uri has no check mode support; this is a GET, so it also runs under --check and drift + # detection sees the live config. + check_mode: false + +- name: Set fact to the actual config dict + no_log: true # the config may hold a stored cipassword (update.yml deletes it) + ansible.builtin.set_fact: + __pve_vm_config: "{{ __pve_vm_current_config.json.data }}" + +- name: Extract current disk string + ansible.builtin.set_fact: + __pve_vm_disk_string: "{{ __pve_vm_config[pve_vm_boot_disk] | default('') }}" + +- name: Extract current disk number and unit properly + ansible.builtin.set_fact: + __pve_vm_disk_parts: "{{ __pve_vm_disk_string | regex_findall('size=(\\d+)([GM])') | first | default(['0', 'G']) | list }}" + +- name: Extract current disk number + ansible.builtin.set_fact: + __pve_vm_current_disk_size_number: "{{ __pve_vm_disk_parts[0] | int }}" + __pve_vm_current_disk_size_unit: "{{ __pve_vm_disk_parts[1] }}" + +- name: Convert disk size to GB + ansible.builtin.set_fact: + __pve_vm_current_disk: >- + {{ + __pve_vm_current_disk_size_number if __pve_vm_current_disk_size_unit == 'G' + else (__pve_vm_current_disk_size_number / 1024) + }} + +- name: Determine if disk resize is needed + ansible.builtin.set_fact: + __pve_vm_resize_disk: "{{ pve_vm_disk_size | regex_replace('[^0-9]', '') | int > __pve_vm_current_disk | int }}" + when: + - pve_vm_manage_disk | bool + - pve_vm_disk_size is defined + - pve_vm_exists diff --git a/roles/pve_vm/tasks/detect_drift.yml b/roles/pve_vm/tasks/detect_drift.yml new file mode 100644 index 0000000..6618c79 --- /dev/null +++ b/roles/pve_vm/tasks/detect_drift.yml @@ -0,0 +1,97 @@ +--- +# community.proxmox.proxmox_kvm with `update: true` reports changed on every run: it does not diff +# against the live config. Compare the config already fetched in detect_disk.yml with the desired +# values and only call the module on real drift or while cloud-init is still unconfigured (first +# run after a clone, when ciuser and sshkeys have to be applied once). Proxmox stores sshkeys +# URL-encoded, so a change is not diffed: pve_vm_force_update pushes it to an existing VM. +- name: Normalise current QEMU guest agent setting + ansible.builtin.set_fact: + # PVE returns "1", "enabled=1" or e.g. "fstrim_cloned_disks=1,enabled=1"; enabled=1 may sit + # in any position. + __pve_vm_agent_current: >- + {{ + '1' if ((__pve_vm_config.agent | default('0') | string).split(',') + | select('in', ['1', 'enabled=1']) | list | length > 0) + else '0' + }} + +- name: Normalise desired and current values for drift comparison + ansible.builtin.set_fact: + # ciuser and sshkeys are only expected in the current config when the role sets them. + __pve_vm_required_config_keys: >- + {{ + (['ciuser'] if (pve_vm_ci_user | string | length > 0) else []) + + (['sshkeys'] if (pve_vm_sshkeys | default('') | string | length > 0) else []) + }} + # PVE returns nameserver space-separated; accept a list or a comma-separated string as well. + __pve_vm_nameservers_desired: >- + {{ + ((pve_vm_nameservers | join(' ')) + if (pve_vm_nameservers | default('') is not string and pve_vm_nameservers | default('') is iterable) + else (pve_vm_nameservers | default('') | string)) + | replace(',', ' ') | split | join(' ') + }} + # ipconfig0 tokens can come back from PVE in a different order. + __pve_vm_ipconfig0_current: "{{ (__pve_vm_config.ipconfig0 | default('') | string).split(',') | sort }}" + __pve_vm_ipconfig0_desired: "{{ (pve_vm_ipconfig.ipconfig0 | default('') | string).split(',') | sort }}" + __pve_vm_net0_current: "{{ (__pve_vm_config.net0 | default('') | string).split(',') }}" + +# autostart is not compared: PVE has no such VM config key (the config API does not return it). +# One fact per drift dimension, combined in __pve_vm_needs_update below. +- name: Determine drift per configuration dimension + ansible.builtin.set_fact: + __pve_vm_drift_forced: >- + {{ + (pve_vm_force_update | bool) + or (__pve_vm_created | default(false) | bool) + }} + __pve_vm_drift_missing_keys: "{{ __pve_vm_required_config_keys | reject('in', __pve_vm_config) | list | length > 0 }}" + __pve_vm_drift_name: "{{ (__pve_vm_config.name | default('')) != (inventory_hostname | lower | replace('_', '-')) }}" + # PVE may return "host" or "cputype=host" (optionally followed by flags). + __pve_vm_drift_cpu: >- + {{ + (__pve_vm_config.cpu | default('') | string).split(',')[0] | regex_replace('^cputype=', '') != 'host' + }} + __pve_vm_drift_resources: >- + {{ + (pve_vm_memory is defined and (__pve_vm_config.memory | default(0) | int) != (pve_vm_memory | int)) + or (pve_vm_cores is defined and (__pve_vm_config.cores | default(1) | int) != (pve_vm_cores | int)) + or (pve_vm_sockets is defined and (__pve_vm_config.sockets | default(1) | int) != (pve_vm_sockets | int)) + }} + __pve_vm_drift_ciuser: "{{ (pve_vm_ci_user | string | length > 0) and __pve_vm_config.ciuser | default('') != pve_vm_ci_user }}" + __pve_vm_drift_ipconfig: "{{ pve_vm_ipconfig.ipconfig0 is defined and __pve_vm_ipconfig0_current != __pve_vm_ipconfig0_desired }}" + __pve_vm_drift_nameservers: >- + {{ pve_vm_nameservers is defined and (__pve_vm_config.nameserver | default('')) != __pve_vm_nameservers_desired }} + __pve_vm_drift_onboot: "{{ (__pve_vm_config.onboot | default(0) | int) != (pve_vm_onboot | bool | int) }}" + __pve_vm_drift_agent: "{{ __pve_vm_agent_current != ((pve_vm_agent | bool | int) | string) }}" + __pve_vm_drift_network: >- + {{ + pve_vm_network.net0 is defined and ( + not (__pve_vm_config.net0 | default('')).startswith(pve_vm_network.net0.model | default('virtio') ~ '=') + or (pve_vm_network.net0.bridge is defined + and ('bridge=' ~ pve_vm_network.net0.bridge) not in __pve_vm_net0_current) + or (pve_vm_network.net0.tag is defined + and ('tag=' ~ pve_vm_network.net0.tag) not in __pve_vm_net0_current) + or (pve_vm_network.net0.tag is not defined + and (__pve_vm_net0_current | select('match', '^tag=') | list | length > 0)) + or (pve_vm_network.net0.firewall is defined + and (('firewall=1' in __pve_vm_net0_current) != (pve_vm_network.net0.firewall | bool))) + ) + }} + +- name: Determine if VM configuration needs updating + ansible.builtin.set_fact: + __pve_vm_needs_update: >- + {{ + __pve_vm_drift_forced | bool + or __pve_vm_drift_missing_keys | bool + or __pve_vm_drift_name | bool + or __pve_vm_drift_cpu | bool + or __pve_vm_drift_resources | bool + or __pve_vm_drift_ciuser | bool + or __pve_vm_drift_ipconfig | bool + or __pve_vm_drift_nameservers | bool + or __pve_vm_drift_onboot | bool + or __pve_vm_drift_agent | bool + or __pve_vm_drift_network | bool + }} diff --git a/roles/pve_vm/tasks/main.yml b/roles/pve_vm/tasks/main.yml new file mode 100644 index 0000000..2ff73c7 --- /dev/null +++ b/roles/pve_vm/tasks/main.yml @@ -0,0 +1,90 @@ +--- +# Validation first, under always, so a bad input fails before any change whatever tags the run +# selects. +- name: Validate the role inputs + ansible.builtin.import_tasks: validate.yml + tags: always + +# Every Proxmox API call of the role is inside this block, so the credentials are set once here +# instead of on each task; module_defaults set on a block reach tasks run through include_tasks. +# They are templated per task and no secret is stored as a fact. The uri call (detect_disk) takes +# host and header explicitly. +- name: Manage Proxmox VM lifecycle + module_defaults: + community.proxmox.proxmox_kvm: + api_user: "{{ pve_vm_api_user }}@{{ pve_vm_api_realm }}" + api_token_id: "{{ pve_vm_api_token_id }}" + api_token_secret: "{{ pve_vm_api_token_secret }}" + api_host: "{{ pve_vm_api_host }}" + validate_certs: false + community.proxmox.proxmox_disk: + api_user: "{{ pve_vm_api_user }}@{{ pve_vm_api_realm }}" + api_token_id: "{{ pve_vm_api_token_id }}" + api_token_secret: "{{ pve_vm_api_token_secret }}" + api_host: "{{ pve_vm_api_host }}" + validate_certs: false + ansible.builtin.uri: + validate_certs: false + block: + - name: Gather current VM information + ansible.builtin.include_tasks: detect.yml + + - name: Remove VM if destruction is requested + ansible.builtin.include_tasks: delete.yml + when: + - pve_vm_state == "absent" + - pve_vm_allow_destroy | bool + - pve_vm_exists + + - name: Stop processing for deleted VM + ansible.builtin.meta: end_host + when: + - pve_vm_state == "absent" + - pve_vm_allow_destroy | bool + + - name: Create VM if it does not exist + ansible.builtin.include_tasks: create.yml + when: + - pve_vm_state != "absent" + - not pve_vm_exists + - not ansible_check_mode + + - name: Preview VM creation + ansible.builtin.debug: + msg: >- + VM {{ pve_vm_vmid }} does not exist on {{ pve_vm_node }}: a real run clones it from template + {{ pve_vm_clone_vmid | default('(unset)') }} and then configures it. Nothing after the lookup runs for it + in this check. + changed_when: true + when: + - pve_vm_state != "absent" + - not pve_vm_exists + - ansible_check_mode + + - name: Refresh VM information after changes + ansible.builtin.include_tasks: detect.yml + + - name: Gather current VM disk information + ansible.builtin.include_tasks: detect_disk.yml + when: + - pve_vm_exists + - pve_vm_state != "absent" + + - name: Update existing VM configuration + ansible.builtin.include_tasks: update.yml + when: + - pve_vm_state != "absent" + - pve_vm_exists + + - name: Ensure VM power state + ansible.builtin.include_tasks: state.yml + when: + - pve_vm_exists + - pve_vm_state in ["started", "stopped"] + + - name: Wait for VM to become ready + ansible.builtin.include_tasks: wait.yml + when: + - pve_vm_exists + - pve_vm_state == "started" + - pve_vm_wait_for_guest | bool diff --git a/roles/pve_vm/tasks/state.yml b/roles/pve_vm/tasks/state.yml new file mode 100644 index 0000000..e816177 --- /dev/null +++ b/roles/pve_vm/tasks/state.yml @@ -0,0 +1,18 @@ +--- +# Under --check the module (no check mode support) does not run; the preview compares the status the +# lookup in detect.yml read with the desired state. +- name: Preview VM power state + ansible.builtin.debug: + msg: "VM {{ pve_vm_vmid }} is {{ __pve_vm_info.status | default('unknown') }}, desired {{ pve_vm_state }}" + changed_when: >- + (__pve_vm_info.status | default('unknown')) != ('running' if pve_vm_state == 'started' else 'stopped') + when: ansible_check_mode + +- name: Ensure VM state + no_log: true # defence in depth: the module already masks the API token secret + delegate_to: "{{ pve_vm_delegate }}" + community.proxmox.proxmox_kvm: + node: "{{ pve_vm_node }}" + vmid: "{{ pve_vm_vmid }}" + state: "{{ pve_vm_state }}" + when: not ansible_check_mode diff --git a/roles/pve_vm/tasks/update.yml b/roles/pve_vm/tasks/update.yml new file mode 100644 index 0000000..1a15984 --- /dev/null +++ b/roles/pve_vm/tasks/update.yml @@ -0,0 +1,126 @@ +--- +- name: Detect VM configuration drift + ansible.builtin.include_tasks: detect_drift.yml + +# Names only, no values: the drift facts are booleans, and sshkeys are never compared. +# Under --check this is the preview of the update and resize below (changed when either would run). +- name: Report configuration drift + ansible.builtin.debug: + msg: >- + {{ + 'drift: ' ~ (__pve_vm_drift_dimensions | join(', ')) if __pve_vm_drift_dimensions | length > 0 + else 'no drift' + }}{{ + '; boot disk resize: ' ~ __pve_vm_current_disk ~ 'G -> ' ~ pve_vm_disk_size + if (pve_vm_manage_disk and __pve_vm_resize_disk | default(false) | bool) else '' + }} + vars: + __pve_vm_drift_dimensions: >- + {{ + [ + 'forced' if __pve_vm_drift_forced | bool else '', + 'missing_keys' if __pve_vm_drift_missing_keys | bool else '', + 'name' if __pve_vm_drift_name | bool else '', + 'cpu' if __pve_vm_drift_cpu | bool else '', + 'resources' if __pve_vm_drift_resources | bool else '', + 'ciuser' if __pve_vm_drift_ciuser | bool else '', + 'ipconfig' if __pve_vm_drift_ipconfig | bool else '', + 'nameservers' if __pve_vm_drift_nameservers | bool else '', + 'onboot' if __pve_vm_drift_onboot | bool else '', + 'agent' if __pve_vm_drift_agent | bool else '', + 'network' if __pve_vm_drift_network | bool else '', + ] | select | list + }} + changed_when: >- + ansible_check_mode and (__pve_vm_needs_update | bool + or (pve_vm_manage_disk and __pve_vm_resize_disk | default(false) | bool)) + +- name: Update VM configuration + no_log: true # carries the API token secret + delegate_to: "{{ pve_vm_delegate }}" + community.proxmox.proxmox_kvm: + node: "{{ pve_vm_node }}" + vmid: "{{ pve_vm_vmid }}" + name: "{{ inventory_hostname | lower | replace('_', '-') }}" + + memory: "{{ pve_vm_memory | default(omit) }}" + cores: "{{ pve_vm_cores | default(omit) }}" + sockets: "{{ pve_vm_sockets | default(omit) }}" + cpu: host + + net: "{{ pve_vm_network | default(omit) }}" + + ciuser: "{{ pve_vm_ci_user if (pve_vm_ci_user | length > 0) else omit }}" + ipconfig: "{{ pve_vm_ipconfig | default(omit) }}" + sshkeys: "{{ pve_vm_sshkeys | default(omit) }}" + nameservers: "{{ pve_vm_nameservers | default(omit) }}" + + agent: "{{ pve_vm_agent }}" + onboot: "{{ pve_vm_onboot }}" + autostart: "{{ pve_vm_autostart }}" + + update: true + state: present + # Explicit: the module has no check mode support, so --check skips it anyway; the report above is the preview. + when: + - __pve_vm_needs_update | bool + - not ansible_check_mode + +# The role never sets a cloud-init password; a VM configured by other means may still have one +# stored. The module cannot combine delete with update, has no check mode and always reports +# changed, hence a separate task, run only when the key is present, with the debug as its --check +# preview. +- name: Preview deletion of the stored cloud-init password + ansible.builtin.debug: + msg: "cipassword stored on VM {{ pve_vm_vmid }}: a real run deletes it" + changed_when: true + when: + - "'cipassword' in __pve_vm_config" + - ansible_check_mode + +- name: Delete the stored cloud-init password + no_log: true # carries the API token secret + delegate_to: "{{ pve_vm_delegate }}" + community.proxmox.proxmox_kvm: + node: "{{ pve_vm_node }}" + vmid: "{{ pve_vm_vmid }}" + delete: cipassword + when: + - "'cipassword' in __pve_vm_config" + - not ansible_check_mode + +# The marker has been consumed by drift detection and the update above; reset it so another +# pve_vm run for this host in the same play does not force a second update. +- name: Clear the just-cloned marker + ansible.builtin.set_fact: + __pve_vm_created: false + +- name: Resize boot drive + no_log: true # defence in depth: the module already masks the API token secret + delegate_to: "{{ pve_vm_delegate }}" + community.proxmox.proxmox_disk: + vmid: "{{ pve_vm_vmid }}" + disk: "{{ pve_vm_boot_disk }}" + size: "{{ pve_vm_disk_size }}" + state: resized + when: + - pve_vm_manage_disk | bool + - __pve_vm_resize_disk + - not ansible_check_mode + register: __pve_vm_disk_resize + +- name: Track disk resize result + ansible.builtin.set_fact: + __pve_vm_disk_resized: "{{ __pve_vm_disk_resize.changed | default(false) }}" + +- name: Restart VM if disk was resized + no_log: true # defence in depth: the module already masks the API token secret + delegate_to: "{{ pve_vm_delegate }}" + community.proxmox.proxmox_kvm: + node: "{{ pve_vm_node }}" + vmid: "{{ pve_vm_vmid }}" + state: restarted + when: + - __pve_vm_disk_resized + - pve_vm_reboot_if_required | bool + - not ansible_check_mode diff --git a/roles/pve_vm/tasks/validate.yml b/roles/pve_vm/tasks/validate.yml new file mode 100644 index 0000000..46aea7e --- /dev/null +++ b/roles/pve_vm/tasks/validate.yml @@ -0,0 +1,28 @@ +--- +# The input rules the argument spec cannot express. main.yml imports this file under +# tags: always, before any change; each assert keeps the condition under which its input is read. + +# Every run calls the API: even pve_vm_state absent without pve_vm_allow_destroy looks the VM up. +- name: Assert the Proxmox API credentials are set + ansible.builtin.assert: + that: + - pve_vm_api_user | length > 0 + - pve_vm_api_token_secret is defined and pve_vm_api_token_secret | length > 0 + fail_msg: >- + The Proxmox API calls need pve_vm_api_user (bare user name, the role appends + @) and pve_vm_api_token_secret (normally vaulted). Neither has a usable + default: set them in the inventory. + quiet: true + +# The update reads the resize flag, which is only computed while pve_vm_disk_size is defined. +- name: Assert the boot disk size is set while the disk is managed + ansible.builtin.assert: + that: + - pve_vm_disk_size is defined + fail_msg: >- + pve_vm_disk_size (for example 32G) must be set while pve_vm_manage_disk is true, the default. + Set pve_vm_manage_disk to false to leave the boot disk alone. + quiet: true + when: + - pve_vm_manage_disk | bool + - pve_vm_state != "absent" diff --git a/roles/pve_vm/tasks/wait.yml b/roles/pve_vm/tasks/wait.yml new file mode 100644 index 0000000..dd11bbe --- /dev/null +++ b/roles/pve_vm/tasks/wait.yml @@ -0,0 +1,16 @@ +--- +- name: Wait for SSH to become available + delegate_to: localhost + ansible.builtin.wait_for: + host: "{{ ansible_host }}" + port: 22 + timeout: 3600 + +# Runs on the guest itself, over the connection the play uses for it. +- name: Wait for cloud-init to finish + ansible.builtin.command: cloud-init status --wait + register: __pve_vm_cloudinit_status + retries: 10 + delay: 15 + until: __pve_vm_cloudinit_status.rc == 0 + changed_when: false diff --git a/roles/pve_vm/vars/main.yml b/roles/pve_vm/vars/main.yml new file mode 100644 index 0000000..5545ea1 --- /dev/null +++ b/roles/pve_vm/vars/main.yml @@ -0,0 +1,4 @@ +--- +# Authorization header of the ansible.builtin.uri call in detect_disk.yml, derived from the +# pve_vm_api_* inputs. +__pve_vm_api_auth_header: "PVEAPIToken={{ pve_vm_api_user }}@{{ pve_vm_api_realm }}!{{ pve_vm_api_token_id }}={{ pve_vm_api_token_secret }}" diff --git a/scripts/run_molecule_scenarios.sh b/scripts/run_molecule_scenarios.sh index 249faf6..149c736 100755 --- a/scripts/run_molecule_scenarios.sh +++ b/scripts/run_molecule_scenarios.sh @@ -116,6 +116,7 @@ declare -A last_seconds=( [roles/user_management/molecule/default]=115 [roles/pihole/molecule/default]=112 [roles/sshd/molecule/default]=65 + [roles/pve_vm/molecule/default]=60 [roles/pve_lxc/molecule/default]=44 [roles/_binary_update/molecule/check_mode]=42 [roles/network_interfaces/molecule/default]=36