From 74732338136e0401edca411c7665a891d11e1800 Mon Sep 17 00:00:00 2001 From: Hermes Agent Date: Fri, 6 Nov 2026 17:43:24 +0000 Subject: [PATCH 01/13] feat(ansible): provision single VM from Semaphore survey --- ansible/provision_vm.yml | 133 ++++++++++++++ ansible/proxmox/semaphore_vm/README.md | 65 +++++++ ansible/proxmox/semaphore_vm/requirements.txt | 2 + ansible/proxmox/semaphore_vm/requirements.yml | 4 + .../proxmox/semaphore_vm/tests/test_flow.py | 172 ++++++++++++++++++ 5 files changed, 376 insertions(+) create mode 100644 ansible/provision_vm.yml create mode 100644 ansible/proxmox/semaphore_vm/README.md create mode 100644 ansible/proxmox/semaphore_vm/requirements.txt create mode 100644 ansible/proxmox/semaphore_vm/requirements.yml create mode 100644 ansible/proxmox/semaphore_vm/tests/test_flow.py diff --git a/ansible/provision_vm.yml b/ansible/provision_vm.yml new file mode 100644 index 0000000..5a4ee10 --- /dev/null +++ b/ansible/provision_vm.yml @@ -0,0 +1,133 @@ +--- +- name: Clone and start one cloud-init VM + hosts: localhost + connection: local + gather_facts: false + vars: + ansible_python_interpreter: "{{ ansible_playbook_python }}" + vm_cpu: 1 + vm_ram_gib: 2 + vm_disk_gib: 4 + vm_vlan: vlan66 + vm_ipconfig0: ip=dhcp + module_defaults: + group/community.proxmox.proxmox: + api_host: "{{ proxmox_api_host }}" + api_port: "{{ proxmox_api_port | default(8006) }}" + api_user: "{{ proxmox_api_token_id.split('!')[0] }}" + api_token_id: "{{ proxmox_api_token_id.split('!')[1] }}" + api_token_secret: "{{ proxmox_api_token_secret }}" + validate_certs: true + tasks: + - name: Validate inputs before using the API + ansible.builtin.assert: + that: + - proxmox_api_host is defined and proxmox_api_host | length > 0 + - proxmox_node is defined and proxmox_node | length > 0 + - vm_template_id is defined and vm_template_id | string is match('^[0-9]+$') + - vm_hostname is defined and vm_hostname is match('^[a-zA-Z0-9][a-zA-Z0-9.-]*$') + - vm_storage is defined and vm_storage | length > 0 + - vm_vlan is defined and vm_vlan is match('^[a-zA-Z0-9_.-]+$') + - vm_user is defined and vm_user | length > 0 + - vm_ssh_public_key is defined and vm_ssh_public_key | length > 0 + - vm_cpu | string is match('^[0-9]+$') and vm_cpu | int > 0 + - vm_ram_gib | string is match('^[0-9]+$') and vm_ram_gib | int > 0 + - vm_disk_gib | string is match('^[0-9]+$') and vm_disk_gib | int > 0 + fail_msg: Required VM inputs are missing or invalid; no VM was created. + + - name: Validate API token inputs + ansible.builtin.assert: + that: + - proxmox_api_token_id is defined and proxmox_api_token_id is match('^[^!]+![^!]+$') + - proxmox_api_token_secret is defined and proxmox_api_token_secret | length > 0 + fail_msg: Configure a Proxmox API token ID and secret in the Semaphore variable group secrets. + no_log: true + + - name: Look up requested hostname across the cluster + community.proxmox.proxmox_vm_info: + name: "{{ vm_hostname }}" + register: named_vm + no_log: true + + - name: Reject an already used hostname + ansible.builtin.assert: + that: named_vm.proxmox_vms | length == 0 + fail_msg: "Hostname {{ vm_hostname }} already exists; no VM was modified. Inspect it before retrying." + + - name: Look up source template and its current configuration + community.proxmox.proxmox_vm_info: + vmid: "{{ vm_template_id }}" + type: qemu + config: current + register: source_vm + no_log: true + + - name: Require a cloud-init-ready template on the selected node + ansible.builtin.assert: + that: + - source_vm.proxmox_vms | length == 1 + - source_vm.proxmox_vms[0].node == proxmox_node + - source_vm.proxmox_vms[0].template | bool + - source_vm.proxmox_vms[0].config.scsi0 is defined + - source_vm.proxmox_vms[0].config.scsi1 is defined + - "'cloudinit' in source_vm.proxmox_vms[0].config.scsi1" + fail_msg: "Template {{ vm_template_id }} must be a QEMU template on {{ proxmox_node }} with scsi0 and a scsi1 cloud-init drive; no VM was created." + + - name: Clone full VM onto requested storage + community.proxmox.proxmox_kvm: + clone: source-template + vmid: "{{ vm_template_id }}" + name: "{{ vm_hostname }}" + node: "{{ proxmox_node }}" + storage: "{{ vm_storage }}" + full: true + state: present + register: cloned_vm + no_log: true + + - name: Stop if cloning did not allocate a new VMID + ansible.builtin.assert: + that: + - cloned_vm.changed + - cloned_vm.vmid is defined + - cloned_vm.vmid | string is match('^[0-9]+$') + - cloned_vm.vmid | int >= 100 + - cloned_vm.vmid | int != vm_template_id | int + fail_msg: >- + Clone did not return a valid new VMID (possibly allocated concurrently); + no configuration was attempted. Inspect the cluster before retrying. + + - name: Configure VM before first boot + community.proxmox.proxmox_kvm: + vmid: "{{ cloned_vm.vmid }}" + node: "{{ proxmox_node }}" + update: true + update_unsafe: true # Needed to replace net0 on this newly cloned VM. + cores: "{{ vm_cpu }}" + memory: "{{ vm_ram_gib | int * 1024 }}" + net: + net0: "virtio,bridge={{ vm_vlan }}" + ipconfig: + ipconfig0: "{{ vm_ipconfig0 }}" + ciuser: "{{ vm_user }}" + sshkeys: "{{ vm_ssh_public_key }}" + state: present + no_log: true + + - name: Grow cloned scsi0 disk to requested size + community.proxmox.proxmox_disk: + vmid: "{{ cloned_vm.vmid }}" + disk: scsi0 + size: "{{ vm_disk_gib }}G" + state: resized + no_log: true + + - name: Start configured VM + community.proxmox.proxmox_kvm: + vmid: "{{ cloned_vm.vmid }}" + state: started + no_log: true + + - name: Report submitted VMID + ansible.builtin.debug: + msg: "VMID {{ cloned_vm.vmid }} start requested; cloud-init completion is not checked." diff --git a/ansible/proxmox/semaphore_vm/README.md b/ansible/proxmox/semaphore_vm/README.md new file mode 100644 index 0000000..4aaf0e9 --- /dev/null +++ b/ansible/proxmox/semaphore_vm/README.md @@ -0,0 +1,65 @@ +# Semaphore single Proxmox VM + +`ansible/provision_vm.yml` clones one existing cloud-init-ready QEMU template, configures CPU, RAM, network, cloud-init user/key and disk while stopped, then starts it. This is one-shot provisioning, not reconciliation; no Terraform state, SSH, guest readiness check, or automatic deletion. + +## Runner and fixed configuration + +Create an Ansible task template in Semaphore pointing to `ansible/provision_vm.yml` and a localhost inventory (`localhost ansible_connection=local`). The runner needs API reachability and a supported Python environment. Install Ansible Core, Python dependencies and the pinned real collection in that environment: + +```sh +python3 -m pip install ansible-core -r ansible/proxmox/semaphore_vm/requirements.txt +ansible-galaxy collection install -r ansible/proxmox/semaphore_vm/requirements.yml +``` + +Assign a Semaphore Variable Group to the template. Put `proxmox_api_token_id` (full `user@realm!token` identifier) and `proxmox_api_token_secret` in the group's **Secrets** tab. The playbook splits the full token identifier into the module's `api_user=user@realm` and `api_token_id=token`. Do not expose these as survey inputs or commit them. Restrict token permissions and template launch access. API tasks use `no_log`; avoid verbose secret logging. TLS verification is enabled; trust the Proxmox CA in the runner. Never disable TLS verification. + +Set these **fixed, non-survey** values in the Variable Group JSON, using inventory-approved choices (the placeholders below are not deployment values): + +```json +{ + "proxmox_api_host": "pve.example.invalid", + "proxmox_node": "example-node", + "vm_template_id": 900, + "vm_storage": "example-storage", + "vm_user": "example-user", + "vm_ssh_public_key": "ssh-ed25519 AAAAexamplePublicKey replace-with-your-own-public-key" +} +``` + +`proxmox_api_host` is a hostname, not a URL. `proxmox_api_port` defaults to 8006 and can be fixed in the group if different. `vm_ipconfig0` defaults to `ip=dhcp` and can be fixed in the group if an approved static configuration is required. `vm_template_id` must refer to a QEMU template on `proxmox_node`, with a bootable `scsi0` and `scsi1` cloud-init drive; `vm_storage` is the full-clone destination. The admin user and SSH **public** key are fixed configuration, not survey prompts. Never put a private key in `vm_ssh_public_key`. + +## Survey: exactly five inputs + +Map the Semaphore labels to these Ansible variable names; only hostname is required without a default: + +| Survey label | Variable | Default | Meaning | +| --- | --- | --- | --- | +| Hostname | `vm_hostname` | required | New, unique VM name / hostname | +| CPU | `vm_cpu` | `1` | Cores | +| RAM (GiB) | `vm_ram_gib` | `2` | GiB; multiplied by 1024 for Proxmox memory in MiB | +| Disk size (GiB) | `vm_disk_gib` | `4` | Absolute requested `scsi0` size in GiB, not an increment | +| VLAN | `vm_vlan` | `vlan66` | Existing Proxmox VNet/bridge identifier used as `net0` bridge | + +These CPU, RAM and disk defaults come from `terraform/projects/simple-vm/variables.tf` (`vm_cpu=1`, `vm_ram=2048` MB) and `terraform/projects/simple-vm/main.tf` (`disk.size=4` GB). Here 2048 MiB / 1024 = 2 GiB, and the playbook sends `2 * 1024 = 2048` MiB. Terraform's `vm_name` has no default. Its `vm_vlan=66` is interpolated into `bridge = "vlan${var.vm_vlan}"`; therefore `vlan66` is a bridge/VNet name, **not** a numeric VLAN tag to set on a separate bridge. The explicitly requested survey default is the literal `vlan66`. Do not supply an unapproved bridge name. The requested disk cannot be smaller than the template's `scsi0`. + +Non-secret example survey JSON: + +```json +{"vm_hostname":"example-vm","vm_cpu":1,"vm_ram_gib":2,"vm_disk_gib":4,"vm_vlan":"vlan66"} +``` + +For manual invocation, store fixed and survey non-secret variables in local JSON files outside this public repository and token variables in an encrypted Ansible Vault file outside it. Do not place credentials on the command line: + +```sh +ansible-playbook -i localhost, -c local ansible/provision_vm.yml \ + -e @/path/to/fixed-config.json -e @/path/to/survey.json \ + -e @/path/to/encrypted-token.yml --ask-vault-pass +``` + +The Terraform project additionally uploads custom cloud-config (packages, guest agent, sudo and reboot), enables the agent, and specifies BIOS/machine and other settings. This playbook does **not** reproduce those customizations. Verify that the chosen template supplies everything required before launch. + +## Allocation, failures and rollback + +The playbook first rejects an existing cluster-wide VM name. The pinned `community.proxmox.proxmox_kvm` clone module fetches the next free cluster VMID using Proxmox `/cluster/nextid` when `newid` is omitted, rejects an occupied ID, and returns the allocated `vmid`. The playbook checks `changed` and a valid returned VMID before configuring it; API allocation/clone failures stop execution. This is **not** a reservation or global uniqueness lock: simultaneous requests can race for a name or VMID, and VM names need not be unique in Proxmox. Do not launch duplicate names concurrently. If an API operation fails after clone, inspect the cluster and Semaphore log for the allocated ID before retrying; the VM may be partial, stopped or running. Do not blindly retry or delete it. Captain handles repair/removal manually. + +API task completion or a powered-on VM does **not** prove guest cloud-init finished. Only Captain launches or reverses infrastructure changes. For code rollback, revert the scoped feature-branch commit; do not rewrite published branch history. Record any applied infrastructure change in the Obsidian vault. diff --git a/ansible/proxmox/semaphore_vm/requirements.txt b/ansible/proxmox/semaphore_vm/requirements.txt new file mode 100644 index 0000000..f7e5865 --- /dev/null +++ b/ansible/proxmox/semaphore_vm/requirements.txt @@ -0,0 +1,2 @@ +proxmoxer>=2.3,<3 +requests>=2.31,<3 diff --git a/ansible/proxmox/semaphore_vm/requirements.yml b/ansible/proxmox/semaphore_vm/requirements.yml new file mode 100644 index 0000000..e0d5860 --- /dev/null +++ b/ansible/proxmox/semaphore_vm/requirements.yml @@ -0,0 +1,4 @@ +--- +collections: + - name: community.proxmox + version: "2.0.0" diff --git a/ansible/proxmox/semaphore_vm/tests/test_flow.py b/ansible/proxmox/semaphore_vm/tests/test_flow.py new file mode 100644 index 0000000..a0e08e2 --- /dev/null +++ b/ansible/proxmox/semaphore_vm/tests/test_flow.py @@ -0,0 +1,172 @@ +"""Offline Ansible control-flow smoke tests; no Proxmox connection is made.""" +import json +import os +from pathlib import Path +import subprocess +import tempfile +import unittest +from proxmoxer.backends.https import ProxmoxHTTPApiTokenAuth +from requests import Request + +ROOT = Path(__file__).resolve().parents[1] +PLAYBOOK = ROOT.parents[1] / "provision_vm.yml" +COLLECTION = "community/proxmox/plugins/modules" +MOCK = '''#!/usr/bin/python +import json +import os +from ansible.module_utils.basic import AnsibleModule + +kind = __file__.rsplit('/', 1)[-1].removesuffix('.py') +fields = ('api_host', 'api_port', 'api_user', 'api_token_id', 'api_token_secret', + 'validate_certs', 'vmid', 'node', 'type', 'config', 'clone', 'newid', + 'name', 'storage', 'full', 'update', 'update_unsafe', 'cores', + 'memory', 'net', 'ipconfig', 'ciuser', 'sshkeys', 'state', 'disk', 'size') +module = AnsibleModule(argument_spec={key: dict(type='raw') for key in fields}) +p = module.params +with open(os.environ['MOCK_LOG'], 'a', encoding='utf-8') as log: + log.write(json.dumps({'kind': kind, 'state': p['state'], + 'api_user': p['api_user'], 'api_token_id': p['api_token_id'], + 'vmid': p['vmid'], 'newid': p['newid'], + 'name': p['name'], 'cores': p['cores'], 'memory': p['memory'], + 'disk': p['disk'], 'size': p['size'], + 'net': p['net'], 'ipconfig': p['ipconfig']}) + '\\n') +scenario = os.environ['MOCK_SCENARIO'] +if kind == 'proxmox_vm_info': + if p['vmid'] == 900: + module.exit_json(changed=False, proxmox_vms=[{ + 'node': 'example-node', 'template': True, + 'config': {'scsi0': 'store:vm-900-disk-0,size=2G', + 'scsi1': 'store:cloudinit'}}]) + module.exit_json(changed=False, proxmox_vms=[{'vmid': 250}] if scenario == 'collision' else []) +if scenario == 'clone_failure' and p['clone']: + module.fail_json(msg='simulated clone failure') +if scenario == 'allocation_failure' and p['clone']: + module.fail_json(msg='unable to retrieve next free vmid') +if scenario == 'race' and p['clone']: + module.exit_json(changed=False) +if scenario == 'missing_id' and p['clone']: + module.exit_json(changed=True) +module.exit_json(changed=True, vmid=(99 if scenario == 'invalid_id' else 250) if p['clone'] else p['vmid']) +''' + + +class ProvisionFlow(unittest.TestCase): + def run_scenario(self, scenario, overrides=None): + with tempfile.TemporaryDirectory() as tmp: + path = Path(tmp) + modules = path / 'ansible_collections' / COLLECTION + modules.mkdir(parents=True) + meta = modules.parent.parent / 'meta' + meta.mkdir() + (meta / 'runtime.yml').write_text( + 'action_groups:\n proxmox:\n - proxmox_vm_info\n' + ' - proxmox_kvm\n - proxmox_disk\n', encoding='utf-8') + for name in ('proxmox_vm_info', 'proxmox_kvm', 'proxmox_disk'): + (modules / f'{name}.py').write_text(MOCK, encoding='utf-8') + log = path / 'calls.jsonl' + env = dict(os.environ, + ANSIBLE_COLLECTIONS_PATH=str(path), + ANSIBLE_LOCAL_TEMP=str(path / 'local'), + MOCK_LOG=str(log), MOCK_SCENARIO=scenario) + variables = dict(proxmox_api_host='example.invalid', + proxmox_api_token_id='offline@pam!test', + proxmox_api_token_secret='not-a-real-secret', + proxmox_node='example-node', vm_template_id=900, + vm_hostname='test-vm', vm_storage='store', vm_user='testuser', + vm_ssh_public_key='ssh-ed25519 AAAAoffline test') + variables.update(overrides or {}) + result = subprocess.run( + ['ansible-playbook', '-i', 'localhost,', '-c', 'local', + str(PLAYBOOK), '-e', json.dumps(variables)], + env=env, capture_output=True, text=True, check=False) + calls = [json.loads(line) for line in log.read_text().splitlines()] if log.exists() else [] + return result, calls + + def test_collision_stops_before_any_write(self): + result, calls = self.run_scenario('collision') + self.assertNotEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertIn('already exists', result.stdout) + self.assertEqual([c['kind'] for c in calls], ['proxmox_vm_info']) + + def test_success_configures_before_start(self): + result, calls = self.run_scenario('success') + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertEqual([(c['kind'], c['state']) for c in calls], [ + ('proxmox_vm_info', None), ('proxmox_vm_info', None), + ('proxmox_kvm', 'present'), ('proxmox_kvm', 'present'), + ('proxmox_disk', 'resized'), ('proxmox_kvm', 'started')]) + self.assertEqual(calls[2]['vmid'], 900) + self.assertIsNone(calls[2]['newid']) + self.assertEqual(calls[3]['net'], {'net0': 'virtio,bridge=vlan66'}) + self.assertEqual(calls[2]['name'], 'test-vm') + self.assertEqual(calls[3]['memory'], 2048) + self.assertEqual(calls[3]['cores'], 1) + self.assertEqual(calls[3]['ipconfig'], {'ipconfig0': 'ip=dhcp'}) + self.assertEqual((calls[4]['disk'], calls[4]['size']), ('scsi0', '4G')) + self.assertEqual(calls[5]['vmid'], 250) + + def test_survey_values_convert_and_map(self): + result, calls = self.run_scenario('success', dict(vm_hostname='new-vm', vm_cpu=4, + vm_ram_gib=3, vm_disk_gib=9, vm_vlan='vlan88')) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertEqual(calls[3]['memory'], 3072) + self.assertEqual(calls[3]['cores'], 4) + self.assertEqual(calls[3]['net'], {'net0': 'virtio,bridge=vlan88'}) + self.assertEqual(calls[4]['size'], '9G') + + def test_invalid_allocated_vmid_stops_before_configuration(self): + result, calls = self.run_scenario('invalid_id') + self.assertNotEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertEqual([c['kind'] for c in calls], [ + 'proxmox_vm_info', 'proxmox_vm_info', 'proxmox_kvm']) + + def test_missing_allocated_vmid_stops_before_configuration(self): + result, calls = self.run_scenario('missing_id') + self.assertNotEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertEqual([c['kind'] for c in calls], [ + 'proxmox_vm_info', 'proxmox_vm_info', 'proxmox_kvm']) + + def test_allocation_failure_stops_before_configuration(self): + result, calls = self.run_scenario('allocation_failure') + self.assertNotEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertEqual([c['kind'] for c in calls], [ + 'proxmox_vm_info', 'proxmox_vm_info', 'proxmox_kvm']) + + def test_invalid_survey_stops_before_api(self): + result, calls = self.run_scenario('success', {'vm_ram_gib': 0}) + self.assertNotEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertEqual(calls, []) + + def test_token_id_maps_to_proxmoxer_auth_identity(self): + result, calls = self.run_scenario('success') + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertTrue(calls) + for call in calls: + self.assertEqual( + (call['api_user'], call['api_token_id']), + ('offline@pam', 'test'), + ) + request = Request('GET', 'https://example.invalid/').prepare() + ProxmoxHTTPApiTokenAuth( + call['api_user'], call['api_token_id'], 'synthetic-value', + )(request) + self.assertEqual( + request.headers['Authorization'], + 'PVEAPIToken=offline@pam!test=synthetic-value', + ) + + def test_clone_noop_stops_before_configuration(self): + result, calls = self.run_scenario('race') + self.assertNotEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertEqual([c['kind'] for c in calls], [ + 'proxmox_vm_info', 'proxmox_vm_info', 'proxmox_kvm']) + + def test_clone_failure_stops_before_configuration(self): + result, calls = self.run_scenario('clone_failure') + self.assertNotEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertEqual([c['kind'] for c in calls], [ + 'proxmox_vm_info', 'proxmox_vm_info', 'proxmox_kvm']) + + +if __name__ == '__main__': + unittest.main() -- 2.54.0 From 6c402ce9bd2967b33ed9892d29d379258c204fac Mon Sep 17 00:00:00 2001 From: Hermes Agent Date: Fri, 6 Nov 2026 18:35:47 +0000 Subject: [PATCH 02/13] refactor(ansible): relocate Proxmox VM provisioning playbook --- ansible/proxmox/{semaphore_vm => }/README.md | 10 +++++----- ansible/{ => proxmox}/provision_vm.yml | 0 ansible/proxmox/{semaphore_vm => }/requirements.txt | 0 ansible/proxmox/{semaphore_vm => }/requirements.yml | 0 ansible/proxmox/{semaphore_vm => }/tests/test_flow.py | 2 +- 5 files changed, 6 insertions(+), 6 deletions(-) rename ansible/proxmox/{semaphore_vm => }/README.md (86%) rename ansible/{ => proxmox}/provision_vm.yml (100%) rename ansible/proxmox/{semaphore_vm => }/requirements.txt (100%) rename ansible/proxmox/{semaphore_vm => }/requirements.yml (100%) rename ansible/proxmox/{semaphore_vm => }/tests/test_flow.py (99%) diff --git a/ansible/proxmox/semaphore_vm/README.md b/ansible/proxmox/README.md similarity index 86% rename from ansible/proxmox/semaphore_vm/README.md rename to ansible/proxmox/README.md index 4aaf0e9..e5824fa 100644 --- a/ansible/proxmox/semaphore_vm/README.md +++ b/ansible/proxmox/README.md @@ -1,14 +1,14 @@ # Semaphore single Proxmox VM -`ansible/provision_vm.yml` clones one existing cloud-init-ready QEMU template, configures CPU, RAM, network, cloud-init user/key and disk while stopped, then starts it. This is one-shot provisioning, not reconciliation; no Terraform state, SSH, guest readiness check, or automatic deletion. +`ansible/proxmox/provision_vm.yml` clones one existing cloud-init-ready QEMU template, configures CPU, RAM, network, cloud-init user/key and disk while stopped, then starts it. This is one-shot provisioning, not reconciliation; no Terraform state, SSH, guest readiness check, or automatic deletion. ## Runner and fixed configuration -Create an Ansible task template in Semaphore pointing to `ansible/provision_vm.yml` and a localhost inventory (`localhost ansible_connection=local`). The runner needs API reachability and a supported Python environment. Install Ansible Core, Python dependencies and the pinned real collection in that environment: +Create an Ansible task template in Semaphore pointing to `ansible/proxmox/provision_vm.yml` and a localhost inventory (`localhost ansible_connection=local`). The runner needs API reachability and a supported Python environment. Install Ansible Core, Python dependencies and the pinned real collection in that environment: ```sh -python3 -m pip install ansible-core -r ansible/proxmox/semaphore_vm/requirements.txt -ansible-galaxy collection install -r ansible/proxmox/semaphore_vm/requirements.yml +python3 -m pip install ansible-core -r ansible/proxmox/requirements.txt +ansible-galaxy collection install -r ansible/proxmox/requirements.yml ``` Assign a Semaphore Variable Group to the template. Put `proxmox_api_token_id` (full `user@realm!token` identifier) and `proxmox_api_token_secret` in the group's **Secrets** tab. The playbook splits the full token identifier into the module's `api_user=user@realm` and `api_token_id=token`. Do not expose these as survey inputs or commit them. Restrict token permissions and template launch access. API tasks use `no_log`; avoid verbose secret logging. TLS verification is enabled; trust the Proxmox CA in the runner. Never disable TLS verification. @@ -51,7 +51,7 @@ Non-secret example survey JSON: For manual invocation, store fixed and survey non-secret variables in local JSON files outside this public repository and token variables in an encrypted Ansible Vault file outside it. Do not place credentials on the command line: ```sh -ansible-playbook -i localhost, -c local ansible/provision_vm.yml \ +ansible-playbook -i localhost, -c local ansible/proxmox/provision_vm.yml \ -e @/path/to/fixed-config.json -e @/path/to/survey.json \ -e @/path/to/encrypted-token.yml --ask-vault-pass ``` diff --git a/ansible/provision_vm.yml b/ansible/proxmox/provision_vm.yml similarity index 100% rename from ansible/provision_vm.yml rename to ansible/proxmox/provision_vm.yml diff --git a/ansible/proxmox/semaphore_vm/requirements.txt b/ansible/proxmox/requirements.txt similarity index 100% rename from ansible/proxmox/semaphore_vm/requirements.txt rename to ansible/proxmox/requirements.txt diff --git a/ansible/proxmox/semaphore_vm/requirements.yml b/ansible/proxmox/requirements.yml similarity index 100% rename from ansible/proxmox/semaphore_vm/requirements.yml rename to ansible/proxmox/requirements.yml diff --git a/ansible/proxmox/semaphore_vm/tests/test_flow.py b/ansible/proxmox/tests/test_flow.py similarity index 99% rename from ansible/proxmox/semaphore_vm/tests/test_flow.py rename to ansible/proxmox/tests/test_flow.py index a0e08e2..bb53b47 100644 --- a/ansible/proxmox/semaphore_vm/tests/test_flow.py +++ b/ansible/proxmox/tests/test_flow.py @@ -9,7 +9,7 @@ from proxmoxer.backends.https import ProxmoxHTTPApiTokenAuth from requests import Request ROOT = Path(__file__).resolve().parents[1] -PLAYBOOK = ROOT.parents[1] / "provision_vm.yml" +PLAYBOOK = ROOT / "provision_vm.yml" COLLECTION = "community/proxmox/plugins/modules" MOCK = '''#!/usr/bin/python import json -- 2.54.0 From 4da3fbfc7f75bd81d38f935d170932418fa85d51 Mon Sep 17 00:00:00 2001 From: Hermes Agent Date: Sat, 7 Nov 2026 14:05:56 +0000 Subject: [PATCH 03/13] remove(ansible): drop committed VM verification harness --- ansible/proxmox/tests/test_flow.py | 172 ----------------------------- 1 file changed, 172 deletions(-) delete mode 100644 ansible/proxmox/tests/test_flow.py diff --git a/ansible/proxmox/tests/test_flow.py b/ansible/proxmox/tests/test_flow.py deleted file mode 100644 index bb53b47..0000000 --- a/ansible/proxmox/tests/test_flow.py +++ /dev/null @@ -1,172 +0,0 @@ -"""Offline Ansible control-flow smoke tests; no Proxmox connection is made.""" -import json -import os -from pathlib import Path -import subprocess -import tempfile -import unittest -from proxmoxer.backends.https import ProxmoxHTTPApiTokenAuth -from requests import Request - -ROOT = Path(__file__).resolve().parents[1] -PLAYBOOK = ROOT / "provision_vm.yml" -COLLECTION = "community/proxmox/plugins/modules" -MOCK = '''#!/usr/bin/python -import json -import os -from ansible.module_utils.basic import AnsibleModule - -kind = __file__.rsplit('/', 1)[-1].removesuffix('.py') -fields = ('api_host', 'api_port', 'api_user', 'api_token_id', 'api_token_secret', - 'validate_certs', 'vmid', 'node', 'type', 'config', 'clone', 'newid', - 'name', 'storage', 'full', 'update', 'update_unsafe', 'cores', - 'memory', 'net', 'ipconfig', 'ciuser', 'sshkeys', 'state', 'disk', 'size') -module = AnsibleModule(argument_spec={key: dict(type='raw') for key in fields}) -p = module.params -with open(os.environ['MOCK_LOG'], 'a', encoding='utf-8') as log: - log.write(json.dumps({'kind': kind, 'state': p['state'], - 'api_user': p['api_user'], 'api_token_id': p['api_token_id'], - 'vmid': p['vmid'], 'newid': p['newid'], - 'name': p['name'], 'cores': p['cores'], 'memory': p['memory'], - 'disk': p['disk'], 'size': p['size'], - 'net': p['net'], 'ipconfig': p['ipconfig']}) + '\\n') -scenario = os.environ['MOCK_SCENARIO'] -if kind == 'proxmox_vm_info': - if p['vmid'] == 900: - module.exit_json(changed=False, proxmox_vms=[{ - 'node': 'example-node', 'template': True, - 'config': {'scsi0': 'store:vm-900-disk-0,size=2G', - 'scsi1': 'store:cloudinit'}}]) - module.exit_json(changed=False, proxmox_vms=[{'vmid': 250}] if scenario == 'collision' else []) -if scenario == 'clone_failure' and p['clone']: - module.fail_json(msg='simulated clone failure') -if scenario == 'allocation_failure' and p['clone']: - module.fail_json(msg='unable to retrieve next free vmid') -if scenario == 'race' and p['clone']: - module.exit_json(changed=False) -if scenario == 'missing_id' and p['clone']: - module.exit_json(changed=True) -module.exit_json(changed=True, vmid=(99 if scenario == 'invalid_id' else 250) if p['clone'] else p['vmid']) -''' - - -class ProvisionFlow(unittest.TestCase): - def run_scenario(self, scenario, overrides=None): - with tempfile.TemporaryDirectory() as tmp: - path = Path(tmp) - modules = path / 'ansible_collections' / COLLECTION - modules.mkdir(parents=True) - meta = modules.parent.parent / 'meta' - meta.mkdir() - (meta / 'runtime.yml').write_text( - 'action_groups:\n proxmox:\n - proxmox_vm_info\n' - ' - proxmox_kvm\n - proxmox_disk\n', encoding='utf-8') - for name in ('proxmox_vm_info', 'proxmox_kvm', 'proxmox_disk'): - (modules / f'{name}.py').write_text(MOCK, encoding='utf-8') - log = path / 'calls.jsonl' - env = dict(os.environ, - ANSIBLE_COLLECTIONS_PATH=str(path), - ANSIBLE_LOCAL_TEMP=str(path / 'local'), - MOCK_LOG=str(log), MOCK_SCENARIO=scenario) - variables = dict(proxmox_api_host='example.invalid', - proxmox_api_token_id='offline@pam!test', - proxmox_api_token_secret='not-a-real-secret', - proxmox_node='example-node', vm_template_id=900, - vm_hostname='test-vm', vm_storage='store', vm_user='testuser', - vm_ssh_public_key='ssh-ed25519 AAAAoffline test') - variables.update(overrides or {}) - result = subprocess.run( - ['ansible-playbook', '-i', 'localhost,', '-c', 'local', - str(PLAYBOOK), '-e', json.dumps(variables)], - env=env, capture_output=True, text=True, check=False) - calls = [json.loads(line) for line in log.read_text().splitlines()] if log.exists() else [] - return result, calls - - def test_collision_stops_before_any_write(self): - result, calls = self.run_scenario('collision') - self.assertNotEqual(result.returncode, 0, result.stdout + result.stderr) - self.assertIn('already exists', result.stdout) - self.assertEqual([c['kind'] for c in calls], ['proxmox_vm_info']) - - def test_success_configures_before_start(self): - result, calls = self.run_scenario('success') - self.assertEqual(result.returncode, 0, result.stdout + result.stderr) - self.assertEqual([(c['kind'], c['state']) for c in calls], [ - ('proxmox_vm_info', None), ('proxmox_vm_info', None), - ('proxmox_kvm', 'present'), ('proxmox_kvm', 'present'), - ('proxmox_disk', 'resized'), ('proxmox_kvm', 'started')]) - self.assertEqual(calls[2]['vmid'], 900) - self.assertIsNone(calls[2]['newid']) - self.assertEqual(calls[3]['net'], {'net0': 'virtio,bridge=vlan66'}) - self.assertEqual(calls[2]['name'], 'test-vm') - self.assertEqual(calls[3]['memory'], 2048) - self.assertEqual(calls[3]['cores'], 1) - self.assertEqual(calls[3]['ipconfig'], {'ipconfig0': 'ip=dhcp'}) - self.assertEqual((calls[4]['disk'], calls[4]['size']), ('scsi0', '4G')) - self.assertEqual(calls[5]['vmid'], 250) - - def test_survey_values_convert_and_map(self): - result, calls = self.run_scenario('success', dict(vm_hostname='new-vm', vm_cpu=4, - vm_ram_gib=3, vm_disk_gib=9, vm_vlan='vlan88')) - self.assertEqual(result.returncode, 0, result.stdout + result.stderr) - self.assertEqual(calls[3]['memory'], 3072) - self.assertEqual(calls[3]['cores'], 4) - self.assertEqual(calls[3]['net'], {'net0': 'virtio,bridge=vlan88'}) - self.assertEqual(calls[4]['size'], '9G') - - def test_invalid_allocated_vmid_stops_before_configuration(self): - result, calls = self.run_scenario('invalid_id') - self.assertNotEqual(result.returncode, 0, result.stdout + result.stderr) - self.assertEqual([c['kind'] for c in calls], [ - 'proxmox_vm_info', 'proxmox_vm_info', 'proxmox_kvm']) - - def test_missing_allocated_vmid_stops_before_configuration(self): - result, calls = self.run_scenario('missing_id') - self.assertNotEqual(result.returncode, 0, result.stdout + result.stderr) - self.assertEqual([c['kind'] for c in calls], [ - 'proxmox_vm_info', 'proxmox_vm_info', 'proxmox_kvm']) - - def test_allocation_failure_stops_before_configuration(self): - result, calls = self.run_scenario('allocation_failure') - self.assertNotEqual(result.returncode, 0, result.stdout + result.stderr) - self.assertEqual([c['kind'] for c in calls], [ - 'proxmox_vm_info', 'proxmox_vm_info', 'proxmox_kvm']) - - def test_invalid_survey_stops_before_api(self): - result, calls = self.run_scenario('success', {'vm_ram_gib': 0}) - self.assertNotEqual(result.returncode, 0, result.stdout + result.stderr) - self.assertEqual(calls, []) - - def test_token_id_maps_to_proxmoxer_auth_identity(self): - result, calls = self.run_scenario('success') - self.assertEqual(result.returncode, 0, result.stdout + result.stderr) - self.assertTrue(calls) - for call in calls: - self.assertEqual( - (call['api_user'], call['api_token_id']), - ('offline@pam', 'test'), - ) - request = Request('GET', 'https://example.invalid/').prepare() - ProxmoxHTTPApiTokenAuth( - call['api_user'], call['api_token_id'], 'synthetic-value', - )(request) - self.assertEqual( - request.headers['Authorization'], - 'PVEAPIToken=offline@pam!test=synthetic-value', - ) - - def test_clone_noop_stops_before_configuration(self): - result, calls = self.run_scenario('race') - self.assertNotEqual(result.returncode, 0, result.stdout + result.stderr) - self.assertEqual([c['kind'] for c in calls], [ - 'proxmox_vm_info', 'proxmox_vm_info', 'proxmox_kvm']) - - def test_clone_failure_stops_before_configuration(self): - result, calls = self.run_scenario('clone_failure') - self.assertNotEqual(result.returncode, 0, result.stdout + result.stderr) - self.assertEqual([c['kind'] for c in calls], [ - 'proxmox_vm_info', 'proxmox_vm_info', 'proxmox_kvm']) - - -if __name__ == '__main__': - unittest.main() -- 2.54.0 From e3de9c111c805d22de3c66ec1931ef848e88fcdb Mon Sep 17 00:00:00 2001 From: Hermes Agent Date: Sat, 7 Nov 2026 17:10:51 +0000 Subject: [PATCH 04/13] build(semaphore): consolidate Proxmox runner requirements --- ansible/proxmox/README.md | 72 ++++++------------------------- ansible/proxmox/requirements.txt | 2 - docker/semaphore/requirements.txt | 3 +- 3 files changed, 14 insertions(+), 63 deletions(-) delete mode 100644 ansible/proxmox/requirements.txt diff --git a/ansible/proxmox/README.md b/ansible/proxmox/README.md index e5824fa..897f13c 100644 --- a/ansible/proxmox/README.md +++ b/ansible/proxmox/README.md @@ -1,65 +1,17 @@ -# Semaphore single Proxmox VM +# Provision one Proxmox VM with Semaphore -`ansible/proxmox/provision_vm.yml` clones one existing cloud-init-ready QEMU template, configures CPU, RAM, network, cloud-init user/key and disk while stopped, then starts it. This is one-shot provisioning, not reconciliation; no Terraform state, SSH, guest readiness check, or automatic deletion. +Create an Ansible task template for `ansible/proxmox/provision_vm.yml` with a localhost inventory (`localhost ansible_connection=local`). It clones a cloud-init QEMU template, configures the VM and starts it. -## Runner and fixed configuration +The Semaphore server gets `proxmoxer>=2.3,<3` and `requests>=2.31,<3` from `docker/semaphore/requirements.txt` (mounted from `/appli/docker/semaphore/requirements.txt` to `/etc/semaphore/requirements.txt`); the image installs these on container startup, not merely on mount. Semaphore automatically installs the adjacent `ansible/proxmox/requirements.yml` (`community.proxmox:2.0.0`) unless **Skip Galaxy install** is enabled. -Create an Ansible task template in Semaphore pointing to `ansible/proxmox/provision_vm.yml` and a localhost inventory (`localhost ansible_connection=local`). The runner needs API reachability and a supported Python environment. Install Ansible Core, Python dependencies and the pinned real collection in that environment: +In a Semaphore Variable Group, set fixed `proxmox_api_host` (hostname, not URL), `proxmox_node`, `vm_template_id`, `vm_storage`, `vm_user`, and `vm_ssh_public_key` (public key only). Set `proxmox_api_token_id` (full `user@realm!token`) and `proxmox_api_token_secret` in the group's **Secrets** tab, not the survey. Optional fixed values: `proxmox_api_port` (default 8006) and `vm_ipconfig0` (default `ip=dhcp`). Trust the Proxmox CA in the runner; TLS verification stays enabled. -```sh -python3 -m pip install ansible-core -r ansible/proxmox/requirements.txt -ansible-galaxy collection install -r ansible/proxmox/requirements.yml -``` +| Survey variable | Default | +| --- | --- | +| `vm_hostname` | Required; unique name | +| `vm_cpu` | `1` core | +| `vm_ram_gib` | `2` GiB | +| `vm_disk_gib` | `4` GiB, absolute disk size | +| `vm_vlan` | `vlan66` bridge/VNet name | -Assign a Semaphore Variable Group to the template. Put `proxmox_api_token_id` (full `user@realm!token` identifier) and `proxmox_api_token_secret` in the group's **Secrets** tab. The playbook splits the full token identifier into the module's `api_user=user@realm` and `api_token_id=token`. Do not expose these as survey inputs or commit them. Restrict token permissions and template launch access. API tasks use `no_log`; avoid verbose secret logging. TLS verification is enabled; trust the Proxmox CA in the runner. Never disable TLS verification. - -Set these **fixed, non-survey** values in the Variable Group JSON, using inventory-approved choices (the placeholders below are not deployment values): - -```json -{ - "proxmox_api_host": "pve.example.invalid", - "proxmox_node": "example-node", - "vm_template_id": 900, - "vm_storage": "example-storage", - "vm_user": "example-user", - "vm_ssh_public_key": "ssh-ed25519 AAAAexamplePublicKey replace-with-your-own-public-key" -} -``` - -`proxmox_api_host` is a hostname, not a URL. `proxmox_api_port` defaults to 8006 and can be fixed in the group if different. `vm_ipconfig0` defaults to `ip=dhcp` and can be fixed in the group if an approved static configuration is required. `vm_template_id` must refer to a QEMU template on `proxmox_node`, with a bootable `scsi0` and `scsi1` cloud-init drive; `vm_storage` is the full-clone destination. The admin user and SSH **public** key are fixed configuration, not survey prompts. Never put a private key in `vm_ssh_public_key`. - -## Survey: exactly five inputs - -Map the Semaphore labels to these Ansible variable names; only hostname is required without a default: - -| Survey label | Variable | Default | Meaning | -| --- | --- | --- | --- | -| Hostname | `vm_hostname` | required | New, unique VM name / hostname | -| CPU | `vm_cpu` | `1` | Cores | -| RAM (GiB) | `vm_ram_gib` | `2` | GiB; multiplied by 1024 for Proxmox memory in MiB | -| Disk size (GiB) | `vm_disk_gib` | `4` | Absolute requested `scsi0` size in GiB, not an increment | -| VLAN | `vm_vlan` | `vlan66` | Existing Proxmox VNet/bridge identifier used as `net0` bridge | - -These CPU, RAM and disk defaults come from `terraform/projects/simple-vm/variables.tf` (`vm_cpu=1`, `vm_ram=2048` MB) and `terraform/projects/simple-vm/main.tf` (`disk.size=4` GB). Here 2048 MiB / 1024 = 2 GiB, and the playbook sends `2 * 1024 = 2048` MiB. Terraform's `vm_name` has no default. Its `vm_vlan=66` is interpolated into `bridge = "vlan${var.vm_vlan}"`; therefore `vlan66` is a bridge/VNet name, **not** a numeric VLAN tag to set on a separate bridge. The explicitly requested survey default is the literal `vlan66`. Do not supply an unapproved bridge name. The requested disk cannot be smaller than the template's `scsi0`. - -Non-secret example survey JSON: - -```json -{"vm_hostname":"example-vm","vm_cpu":1,"vm_ram_gib":2,"vm_disk_gib":4,"vm_vlan":"vlan66"} -``` - -For manual invocation, store fixed and survey non-secret variables in local JSON files outside this public repository and token variables in an encrypted Ansible Vault file outside it. Do not place credentials on the command line: - -```sh -ansible-playbook -i localhost, -c local ansible/proxmox/provision_vm.yml \ - -e @/path/to/fixed-config.json -e @/path/to/survey.json \ - -e @/path/to/encrypted-token.yml --ask-vault-pass -``` - -The Terraform project additionally uploads custom cloud-config (packages, guest agent, sudo and reboot), enables the agent, and specifies BIOS/machine and other settings. This playbook does **not** reproduce those customizations. Verify that the chosen template supplies everything required before launch. - -## Allocation, failures and rollback - -The playbook first rejects an existing cluster-wide VM name. The pinned `community.proxmox.proxmox_kvm` clone module fetches the next free cluster VMID using Proxmox `/cluster/nextid` when `newid` is omitted, rejects an occupied ID, and returns the allocated `vmid`. The playbook checks `changed` and a valid returned VMID before configuring it; API allocation/clone failures stop execution. This is **not** a reservation or global uniqueness lock: simultaneous requests can race for a name or VMID, and VM names need not be unique in Proxmox. Do not launch duplicate names concurrently. If an API operation fails after clone, inspect the cluster and Semaphore log for the allocated ID before retrying; the VM may be partial, stopped or running. Do not blindly retry or delete it. Captain handles repair/removal manually. - -API task completion or a powered-on VM does **not** prove guest cloud-init finished. Only Captain launches or reverses infrastructure changes. For code rollback, revert the scoped feature-branch commit; do not rewrite published branch history. Record any applied infrastructure change in the Obsidian vault. +Use a template with bootable `scsi0` and a `scsi1` cloud-init drive; partial failures are not automatically deleted, and starting the VM does not guarantee guest cloud-init readiness. diff --git a/ansible/proxmox/requirements.txt b/ansible/proxmox/requirements.txt deleted file mode 100644 index f7e5865..0000000 --- a/ansible/proxmox/requirements.txt +++ /dev/null @@ -1,2 +0,0 @@ -proxmoxer>=2.3,<3 -requests>=2.31,<3 diff --git a/docker/semaphore/requirements.txt b/docker/semaphore/requirements.txt index fc3ca69..f7e5865 100644 --- a/docker/semaphore/requirements.txt +++ b/docker/semaphore/requirements.txt @@ -1 +1,2 @@ -proxmoxer>=2.3 \ No newline at end of file +proxmoxer>=2.3,<3 +requests>=2.31,<3 -- 2.54.0 From 3d46a68e74314a87fdeefb9709efe2f93c292c46 Mon Sep 17 00:00:00 2001 From: Vezpi Date: Mon, 2 Nov 2026 21:43:13 +0100 Subject: [PATCH 05/13] update(unifi): v10.6.106-ls146 --- docker/unifi/docker-compose.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docker/unifi/docker-compose.yml b/docker/unifi/docker-compose.yml index d695548..844e40f 100644 --- a/docker/unifi/docker-compose.yml +++ b/docker/unifi/docker-compose.yml @@ -1,6 +1,6 @@ services: network_application: - image: lscr.io/linuxserver/unifi-network-application:10.6.101-ls143 + image: lscr.io/linuxserver/unifi-network-application:10.6.106-ls146 container_name: unifi_network_application depends_on: - db -- 2.54.0 From f027febf147555292bcc4279646897944742feeb Mon Sep 17 00:00:00 2001 From: Vezpi Date: Mon, 2 Nov 2026 21:49:50 +0100 Subject: [PATCH 06/13] update(unifi): 10.6.109-ls152 --- docker/unifi/docker-compose.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docker/unifi/docker-compose.yml b/docker/unifi/docker-compose.yml index 844e40f..a2f8061 100644 --- a/docker/unifi/docker-compose.yml +++ b/docker/unifi/docker-compose.yml @@ -1,6 +1,6 @@ services: network_application: - image: lscr.io/linuxserver/unifi-network-application:10.6.106-ls146 + image: lscr.io/linuxserver/unifi-network-application:10.6.109-ls152 container_name: unifi_network_application depends_on: - db -- 2.54.0 From a1aa77fb69d5fe257aac7eaf7b7c110897194f98 Mon Sep 17 00:00:00 2001 From: Vezpi Date: Mon, 2 Nov 2026 22:01:03 +0100 Subject: [PATCH 07/13] update(gitea): v28 --- docker/gitea/docker-compose.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docker/gitea/docker-compose.yml b/docker/gitea/docker-compose.yml index d473f79..e057712 100644 --- a/docker/gitea/docker-compose.yml +++ b/docker/gitea/docker-compose.yml @@ -1,6 +1,6 @@ services: server: - image: gitea/gitea:1.27 + image: gitea/gitea:28 container_name: gitea_server restart: always volumes: -- 2.54.0 From f4909858bf953dd285bcefdee662dd35287a3f23 Mon Sep 17 00:00:00 2001 From: Vezpi Date: Sun, 8 Nov 2026 22:25:02 +0000 Subject: [PATCH 08/13] change(cloudinit): default network to vlan66 --- ansible/proxmox/cloudinit_template.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ansible/proxmox/cloudinit_template.yml b/ansible/proxmox/cloudinit_template.yml index 5ebec9b..652bd89 100644 --- a/ansible/proxmox/cloudinit_template.yml +++ b/ansible/proxmox/cloudinit_template.yml @@ -82,7 +82,7 @@ qm create {{ template_vmid }} --memory {{ template_memory }} --core {{ template_cores }} - --net0 virtio,bridge=vmbr0 + --net0 virtio,bridge=vlan66 --scsihw virtio-scsi-pci --bios ovmf --machine q35 -- 2.54.0 From ee9d19a7814a98f65de442a105e1a99b33c2359a Mon Sep 17 00:00:00 2001 From: Hermes Agent Date: Mon, 9 Nov 2026 09:47:38 +0000 Subject: [PATCH 09/13] feat(ansible): verify provisioned VM by FQDN and cloud-init --- ansible/proxmox/README.md | 8 ++- ansible/proxmox/provision_vm.yml | 99 ++++++++++++++++++++++++++++---- 2 files changed, 93 insertions(+), 14 deletions(-) diff --git a/ansible/proxmox/README.md b/ansible/proxmox/README.md index 897f13c..a31aab3 100644 --- a/ansible/proxmox/README.md +++ b/ansible/proxmox/README.md @@ -1,10 +1,10 @@ # Provision one Proxmox VM with Semaphore -Create an Ansible task template for `ansible/proxmox/provision_vm.yml` with a localhost inventory (`localhost ansible_connection=local`). It clones a cloud-init QEMU template, configures the VM and starts it. +Create an Ansible task template for `ansible/proxmox/provision_vm.yml` with a localhost inventory (`localhost ansible_connection=local`). It discovers the template's current node via the cluster API, clones once, configures before starting, then checks the guest by FQDN. The Semaphore server gets `proxmoxer>=2.3,<3` and `requests>=2.31,<3` from `docker/semaphore/requirements.txt` (mounted from `/appli/docker/semaphore/requirements.txt` to `/etc/semaphore/requirements.txt`); the image installs these on container startup, not merely on mount. Semaphore automatically installs the adjacent `ansible/proxmox/requirements.yml` (`community.proxmox:2.0.0`) unless **Skip Galaxy install** is enabled. -In a Semaphore Variable Group, set fixed `proxmox_api_host` (hostname, not URL), `proxmox_node`, `vm_template_id`, `vm_storage`, `vm_user`, and `vm_ssh_public_key` (public key only). Set `proxmox_api_token_id` (full `user@realm!token`) and `proxmox_api_token_secret` in the group's **Secrets** tab, not the survey. Optional fixed values: `proxmox_api_port` (default 8006) and `vm_ipconfig0` (default `ip=dhcp`). Trust the Proxmox CA in the runner; TLS verification stays enabled. +In a Semaphore Variable Group, set fixed `proxmox_api_host` (hostname, not URL), `vm_template_id`, `vm_storage`, `vm_user`, and `vm_ssh_public_key` (public keys only). One key works as before; multiple keys are newline-delimited, one complete public key per line (for example, `ssh-ed25519 ` followed by `ssh-ed25519 ` on the next line). Include the public key corresponding to the guest SSH credential selected for Semaphore. Set `proxmox_api_token_id` (full `user@realm!token`) and `proxmox_api_token_secret` in the group's **Secrets** tab, not the survey. Optional fixed values: `proxmox_api_port` (default 8006) and `vm_ipconfig0` (default `ip=dhcp`). Trust the Proxmox CA in the runner; TLS verification stays enabled. | Survey variable | Default | | --- | --- | @@ -14,4 +14,6 @@ In a Semaphore Variable Group, set fixed `proxmox_api_host` (hostname, not URL), | `vm_disk_gib` | `4` GiB, absolute disk size | | `vm_vlan` | `vlan66` bridge/VNet name | -Use a template with bootable `scsi0` and a `scsi1` cloud-init drive; partial failures are not automatically deleted, and starting the VM does not guarantee guest cloud-init readiness. +Only `vlan66` maps to `lab.vezpi.com` in the playbook; unknown VLANs fail before API provisioning. `vm_hostname` must be a single short DNS label (no dots). DHCP/DNS must publish `.lab.vezpi.com` for the chosen VNet; a derived name is not proof of a current record. Stale/reused DNS can point at another host: verify record ownership and the new guest's SSH host key out of band before running. Never trust an unverified `ssh-keyscan` result or disable host-key checking. + +Use a template with bootable `scsi0`, a `scsi1` cloud-init drive, Python 3, `cloud-init`, `timeout`, SSH and a reachable guest network. Select an SSH Key Store **user credential on the task inventory** whose private key matches one authorized public key for `vm_user`; the same Ansible invocation's inventory credential must be available to the dynamically added guest (verify this in the installed Semaphore version). The localhost API token is separate. Pre-enroll a verified guest host key in the runner's trusted `known_hosts` using a Captain-approved mechanism; no private key path or trust bypass is configured here. DNS, SSH port, Python-capable Ansible connection, cloud-init wait/status and final Ansible ping are bounded stages. The connection check retries transient transport failures within its timeout; Python 3 is required in the image. Nonzero cloud-init status fails; a failed or timed-out VM remains for Captain to inspect, not delete. No guest agent, package installation, sudo changes or reboot are added. diff --git a/ansible/proxmox/provision_vm.yml b/ansible/proxmox/provision_vm.yml index 5a4ee10..63385f9 100644 --- a/ansible/proxmox/provision_vm.yml +++ b/ansible/proxmox/provision_vm.yml @@ -10,6 +10,8 @@ vm_disk_gib: 4 vm_vlan: vlan66 vm_ipconfig0: ip=dhcp + vm_dns_domains: + vlan66: lab.vezpi.com module_defaults: group/community.proxmox.proxmox: api_host: "{{ proxmox_api_host }}" @@ -23,17 +25,17 @@ ansible.builtin.assert: that: - proxmox_api_host is defined and proxmox_api_host | length > 0 - - proxmox_node is defined and proxmox_node | length > 0 - vm_template_id is defined and vm_template_id | string is match('^[0-9]+$') - - vm_hostname is defined and vm_hostname is match('^[a-zA-Z0-9][a-zA-Z0-9.-]*$') + - vm_hostname is defined and vm_hostname is match('^[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?$') - vm_storage is defined and vm_storage | length > 0 - vm_vlan is defined and vm_vlan is match('^[a-zA-Z0-9_.-]+$') + - vm_vlan in vm_dns_domains - vm_user is defined and vm_user | length > 0 - - vm_ssh_public_key is defined and vm_ssh_public_key | length > 0 + - vm_ssh_public_key is defined and vm_ssh_public_key | trim | length > 0 - vm_cpu | string is match('^[0-9]+$') and vm_cpu | int > 0 - vm_ram_gib | string is match('^[0-9]+$') and vm_ram_gib | int > 0 - vm_disk_gib | string is match('^[0-9]+$') and vm_disk_gib | int > 0 - fail_msg: Required VM inputs are missing or invalid; no VM was created. + fail_msg: Required VM inputs are invalid (short hostname, known VLAN/DNS suffix and public keys required); no VM was created. - name: Validate API token inputs ansible.builtin.assert: @@ -62,23 +64,28 @@ register: source_vm no_log: true - - name: Require a cloud-init-ready template on the selected node + - name: Require exactly one source template before reading its configuration ansible.builtin.assert: that: - source_vm.proxmox_vms | length == 1 - - source_vm.proxmox_vms[0].node == proxmox_node + fail_msg: "Template {{ vm_template_id }} was missing or ambiguous in the cluster; no VM was created." + + - name: Require a cloud-init-ready template on its current node + ansible.builtin.assert: + that: + - source_vm.proxmox_vms[0].node is defined - source_vm.proxmox_vms[0].template | bool - source_vm.proxmox_vms[0].config.scsi0 is defined - source_vm.proxmox_vms[0].config.scsi1 is defined - "'cloudinit' in source_vm.proxmox_vms[0].config.scsi1" - fail_msg: "Template {{ vm_template_id }} must be a QEMU template on {{ proxmox_node }} with scsi0 and a scsi1 cloud-init drive; no VM was created." + fail_msg: "Template {{ vm_template_id }} must be a QEMU template with a node, scsi0 and a scsi1 cloud-init drive; no VM was created." - name: Clone full VM onto requested storage community.proxmox.proxmox_kvm: clone: source-template vmid: "{{ vm_template_id }}" name: "{{ vm_hostname }}" - node: "{{ proxmox_node }}" + node: "{{ source_vm.proxmox_vms[0].node }}" storage: "{{ vm_storage }}" full: true state: present @@ -100,7 +107,7 @@ - name: Configure VM before first boot community.proxmox.proxmox_kvm: vmid: "{{ cloned_vm.vmid }}" - node: "{{ proxmox_node }}" + node: "{{ source_vm.proxmox_vms[0].node }}" update: true update_unsafe: true # Needed to replace net0 on this newly cloned VM. cores: "{{ vm_cpu }}" @@ -128,6 +135,76 @@ state: started no_log: true - - name: Report submitted VMID + - name: Wait for guest DNS publication + ansible.builtin.command: + argv: + - getent + - ahosts + - "{{ vm_hostname }}.{{ vm_dns_domains[vm_vlan] }}" + register: guest_dns + changed_when: false + until: guest_dns.rc == 0 and guest_dns.stdout | length > 0 + retries: 30 + delay: 5 + + - name: Wait for guest SSH port after DNS resolution + ansible.builtin.wait_for: + host: "{{ vm_hostname }}.{{ vm_dns_domains[vm_vlan] }}" + port: 22 + connect_timeout: 5 + timeout: 180 + sleep: 5 + + - name: Add new guest to ephemeral inventory + ansible.builtin.add_host: + name: "{{ vm_hostname }}.{{ vm_dns_domains[vm_vlan] }}" + groups: provisioned_vm + ansible_connection: ssh + ansible_user: "{{ vm_user }}" + ansible_ssh_timeout: 10 + provisioned_vmid: "{{ cloned_vm.vmid }}" + + - name: Report guest check start ansible.builtin.debug: - msg: "VMID {{ cloned_vm.vmid }} start requested; cloud-init completion is not checked." + msg: "VMID {{ cloned_vm.vmid }} started; DNS and SSH port reachable for {{ vm_hostname }}.{{ vm_dns_domains[vm_vlan] }}. Checking guest SSH, cloud-init and Ansible next." + +- name: Verify cloud-init and Ansible on the new guest + hosts: provisioned_vm + gather_facts: false + tasks: + - name: Wait for Ansible connection with Python + ansible.builtin.wait_for_connection: + connect_timeout: 10 + sleep: 5 + timeout: 180 + + - name: Wait for cloud-init with an external bound + ansible.builtin.raw: timeout 300 cloud-init status --wait + register: cloudinit_wait + changed_when: false + failed_when: false + + - name: Require cloud-init wait to succeed + ansible.builtin.assert: + that: cloudinit_wait.rc == 0 + fail_msg: "VMID {{ provisioned_vmid }} cloud-init wait failed (rc {{ cloudinit_wait.rc }}); VM left intact for inspection." + + - name: Read final cloud-init status + ansible.builtin.raw: cloud-init status + register: cloudinit_status + changed_when: false + failed_when: false + + - name: Require successful completed cloud-init + ansible.builtin.assert: + that: + - cloudinit_status.rc == 0 + - "cloudinit_status.stdout is search('(?m)^status: done\\s*$')" + fail_msg: "VMID {{ provisioned_vmid }} cloud-init status is not successful (rc {{ cloudinit_status.rc }}); VM left intact for inspection." + + - name: Verify final Ansible ping + ansible.builtin.ping: + + - name: Report verified guest readiness + ansible.builtin.debug: + msg: "VMID {{ provisioned_vmid }} at {{ inventory_hostname }} completed cloud-init and returned Ansible pong." -- 2.54.0 From ef9b4454ff5f3de0ce8d0ec733fe7342188a001f Mon Sep 17 00:00:00 2001 From: Hermes Agent Date: Mon, 9 Nov 2026 12:47:58 +0000 Subject: [PATCH 10/13] feat(ansible): accept degraded cloud-init and set guest timezone --- ansible/proxmox/README.md | 2 +- ansible/proxmox/provision_vm.yml | 54 +++++++++++++++++++++++++++----- 2 files changed, 48 insertions(+), 8 deletions(-) diff --git a/ansible/proxmox/README.md b/ansible/proxmox/README.md index a31aab3..1326fb8 100644 --- a/ansible/proxmox/README.md +++ b/ansible/proxmox/README.md @@ -16,4 +16,4 @@ In a Semaphore Variable Group, set fixed `proxmox_api_host` (hostname, not URL), Only `vlan66` maps to `lab.vezpi.com` in the playbook; unknown VLANs fail before API provisioning. `vm_hostname` must be a single short DNS label (no dots). DHCP/DNS must publish `.lab.vezpi.com` for the chosen VNet; a derived name is not proof of a current record. Stale/reused DNS can point at another host: verify record ownership and the new guest's SSH host key out of band before running. Never trust an unverified `ssh-keyscan` result or disable host-key checking. -Use a template with bootable `scsi0`, a `scsi1` cloud-init drive, Python 3, `cloud-init`, `timeout`, SSH and a reachable guest network. Select an SSH Key Store **user credential on the task inventory** whose private key matches one authorized public key for `vm_user`; the same Ansible invocation's inventory credential must be available to the dynamically added guest (verify this in the installed Semaphore version). The localhost API token is separate. Pre-enroll a verified guest host key in the runner's trusted `known_hosts` using a Captain-approved mechanism; no private key path or trust bypass is configured here. DNS, SSH port, Python-capable Ansible connection, cloud-init wait/status and final Ansible ping are bounded stages. The connection check retries transient transport failures within its timeout; Python 3 is required in the image. Nonzero cloud-init status fails; a failed or timed-out VM remains for Captain to inspect, not delete. No guest agent, package installation, sudo changes or reboot are added. +Use a template with bootable `scsi0`, a `scsi1` cloud-init drive, Python 3, `cloud-init`, `timeout`, SSH and a reachable guest network. Select an SSH Key Store **user credential on the task inventory** whose private key matches one authorized public key for `vm_user`; the same Ansible invocation's inventory credential must be available to the dynamically added guest (verify this in the installed Semaphore version). The localhost API token is separate. Pre-enroll a verified guest host key in the runner's trusted `known_hosts` using a Captain-approved mechanism; no private key path or trust bypass is configured here. DNS, SSH port, Python-capable Ansible connection, cloud-init wait/status and final Ansible ping are bounded stages. The connection check retries transient transport failures within its timeout; Python 3 is required in the image. Completed cloud-init status accepts rc 0 or degraded rc 2, prints `--long` diagnostics and warns on rc 2; other codes, incomplete status and timeouts fail. A failed or timed-out VM remains for Captain to inspect, not delete. After accepted cloud-init completion, the guest timezone is verified as `Europe/Paris` (CET/CEST); RTC and NTP are untouched. The guest needs `timedatectl`, timezone data (`tzdata`), and authorized noninteractive sudo/become for `vm_user` when a timezone change is needed. If these are unavailable, readiness fails; no sudo configuration, package installation or reboot is added. diff --git a/ansible/proxmox/provision_vm.yml b/ansible/proxmox/provision_vm.yml index 63385f9..d395cef 100644 --- a/ansible/proxmox/provision_vm.yml +++ b/ansible/proxmox/provision_vm.yml @@ -171,6 +171,8 @@ - name: Verify cloud-init and Ansible on the new guest hosts: provisioned_vm gather_facts: false + vars: + vm_timezone: Europe/Paris tasks: - name: Wait for Ansible connection with Python ansible.builtin.wait_for_connection: @@ -179,28 +181,66 @@ timeout: 180 - name: Wait for cloud-init with an external bound - ansible.builtin.raw: timeout 300 cloud-init status --wait + ansible.builtin.raw: timeout 300 cloud-init status --wait --long register: cloudinit_wait changed_when: false failed_when: false - - name: Require cloud-init wait to succeed + - name: Show cloud-init wait diagnostics + ansible.builtin.debug: + msg: + - "stdout: {{ cloudinit_wait.stdout | trim }}" + - "stderr: {{ cloudinit_wait.stderr | trim }}" + + - name: Require cloud-init wait to complete ansible.builtin.assert: - that: cloudinit_wait.rc == 0 + that: cloudinit_wait.rc in [0, 2] fail_msg: "VMID {{ provisioned_vmid }} cloud-init wait failed (rc {{ cloudinit_wait.rc }}); VM left intact for inspection." - name: Read final cloud-init status - ansible.builtin.raw: cloud-init status + ansible.builtin.raw: cloud-init status --long register: cloudinit_status changed_when: false failed_when: false - - name: Require successful completed cloud-init + - name: Show final cloud-init diagnostics + ansible.builtin.debug: + msg: + - "stdout: {{ cloudinit_status.stdout | trim }}" + - "stderr: {{ cloudinit_status.stderr | trim }}" + + - name: Require completed cloud-init ansible.builtin.assert: that: - - cloudinit_status.rc == 0 + - cloudinit_status.rc in [0, 2] - "cloudinit_status.stdout is search('(?m)^status: done\\s*$')" - fail_msg: "VMID {{ provisioned_vmid }} cloud-init status is not successful (rc {{ cloudinit_status.rc }}); VM left intact for inspection." + fail_msg: "VMID {{ provisioned_vmid }} cloud-init status is not complete (rc {{ cloudinit_status.rc }}); VM left intact for inspection." + + - name: Warn about degraded cloud-init completion + ansible.builtin.debug: + msg: "VMID {{ provisioned_vmid }} cloud-init completed with degraded status (rc 2); individual cloud-init operations may not have succeeded. Inspect the diagnostics before relying on this guest." + when: cloudinit_wait.rc == 2 or cloudinit_status.rc == 2 + + - name: Read guest timezone + ansible.builtin.command: timedatectl show --property=Timezone --value + register: guest_timezone_before + changed_when: false + + - name: Set guest display timezone + ansible.builtin.command: + argv: [timedatectl, set-timezone, "{{ vm_timezone }}"] + become: true + when: guest_timezone_before.stdout | trim != vm_timezone + + - name: Verify guest timezone + ansible.builtin.command: timedatectl show --property=Timezone --value + register: guest_timezone_after + changed_when: false + + - name: Require configured guest timezone + ansible.builtin.assert: + that: guest_timezone_after.stdout | trim == vm_timezone + fail_msg: "VMID {{ provisioned_vmid }} guest timezone did not become {{ vm_timezone }}; VM left intact for inspection." - name: Verify final Ansible ping ansible.builtin.ping: -- 2.54.0 From 9b015b6987ec107e3416ea97927eb4d97753ba8d Mon Sep 17 00:00:00 2001 From: Hermes Agent Date: Mon, 9 Nov 2026 14:09:35 +0000 Subject: [PATCH 11/13] refactor(ansible): trim VM provisioning checks --- ansible/proxmox/README.md | 2 +- ansible/proxmox/provision_vm.yml | 71 ++++---------------------------- 2 files changed, 9 insertions(+), 64 deletions(-) diff --git a/ansible/proxmox/README.md b/ansible/proxmox/README.md index 1326fb8..f39b1d0 100644 --- a/ansible/proxmox/README.md +++ b/ansible/proxmox/README.md @@ -16,4 +16,4 @@ In a Semaphore Variable Group, set fixed `proxmox_api_host` (hostname, not URL), Only `vlan66` maps to `lab.vezpi.com` in the playbook; unknown VLANs fail before API provisioning. `vm_hostname` must be a single short DNS label (no dots). DHCP/DNS must publish `.lab.vezpi.com` for the chosen VNet; a derived name is not proof of a current record. Stale/reused DNS can point at another host: verify record ownership and the new guest's SSH host key out of band before running. Never trust an unverified `ssh-keyscan` result or disable host-key checking. -Use a template with bootable `scsi0`, a `scsi1` cloud-init drive, Python 3, `cloud-init`, `timeout`, SSH and a reachable guest network. Select an SSH Key Store **user credential on the task inventory** whose private key matches one authorized public key for `vm_user`; the same Ansible invocation's inventory credential must be available to the dynamically added guest (verify this in the installed Semaphore version). The localhost API token is separate. Pre-enroll a verified guest host key in the runner's trusted `known_hosts` using a Captain-approved mechanism; no private key path or trust bypass is configured here. DNS, SSH port, Python-capable Ansible connection, cloud-init wait/status and final Ansible ping are bounded stages. The connection check retries transient transport failures within its timeout; Python 3 is required in the image. Completed cloud-init status accepts rc 0 or degraded rc 2, prints `--long` diagnostics and warns on rc 2; other codes, incomplete status and timeouts fail. A failed or timed-out VM remains for Captain to inspect, not delete. After accepted cloud-init completion, the guest timezone is verified as `Europe/Paris` (CET/CEST); RTC and NTP are untouched. The guest needs `timedatectl`, timezone data (`tzdata`), and authorized noninteractive sudo/become for `vm_user` when a timezone change is needed. If these are unavailable, readiness fails; no sudo configuration, package installation or reboot is added. +Use a template with bootable `scsi0`, a `scsi1` cloud-init drive, Python 3, `cloud-init`, `timeout`, SSH and a reachable guest network. Select an SSH Key Store **user credential on the task inventory** whose private key matches one authorized public key for `vm_user`; the same Ansible invocation's inventory credential must be available to the dynamically added guest (verify this in the installed Semaphore version). The localhost API token is separate. Pre-enroll a verified guest host key in the runner's trusted `known_hosts` using a Captain-approved mechanism; no private key path or trust bypass is configured here. DNS, SSH port, Python-capable Ansible connection, cloud-init wait/status and final Ansible ping are bounded stages. The connection check retries transient transport failures within its timeout; Python 3 is required in the image. Completed cloud-init status accepts rc 0 or degraded rc 2, prints `--long` diagnostics and warns on rc 2; other codes, incomplete status and timeouts fail. A failed or timed-out VM remains for Captain to inspect, not delete. After accepted cloud-init completion, the guest timezone is read and, if needed, set to `Europe/Paris` (CET/CEST); RTC and NTP are untouched. The guest needs `timedatectl`, timezone data (`tzdata`), and authorized noninteractive sudo/become for `vm_user` when a timezone change is needed. If these are unavailable, readiness fails; no sudo configuration, package installation or reboot is added. diff --git a/ansible/proxmox/provision_vm.yml b/ansible/proxmox/provision_vm.yml index d395cef..23d9ed3 100644 --- a/ansible/proxmox/provision_vm.yml +++ b/ansible/proxmox/provision_vm.yml @@ -21,29 +21,12 @@ api_token_secret: "{{ proxmox_api_token_secret }}" validate_certs: true tasks: - - name: Validate inputs before using the API + - name: Validate hostname and DNS mapping before using the API ansible.builtin.assert: that: - - proxmox_api_host is defined and proxmox_api_host | length > 0 - - vm_template_id is defined and vm_template_id | string is match('^[0-9]+$') - vm_hostname is defined and vm_hostname is match('^[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?$') - - vm_storage is defined and vm_storage | length > 0 - - vm_vlan is defined and vm_vlan is match('^[a-zA-Z0-9_.-]+$') - vm_vlan in vm_dns_domains - - vm_user is defined and vm_user | length > 0 - - vm_ssh_public_key is defined and vm_ssh_public_key | trim | length > 0 - - vm_cpu | string is match('^[0-9]+$') and vm_cpu | int > 0 - - vm_ram_gib | string is match('^[0-9]+$') and vm_ram_gib | int > 0 - - vm_disk_gib | string is match('^[0-9]+$') and vm_disk_gib | int > 0 - fail_msg: Required VM inputs are invalid (short hostname, known VLAN/DNS suffix and public keys required); no VM was created. - - - name: Validate API token inputs - ansible.builtin.assert: - that: - - proxmox_api_token_id is defined and proxmox_api_token_id is match('^[^!]+![^!]+$') - - proxmox_api_token_secret is defined and proxmox_api_token_secret | length > 0 - fail_msg: Configure a Proxmox API token ID and secret in the Semaphore variable group secrets. - no_log: true + fail_msg: A short hostname and a known VLAN/DNS suffix are required; no VM was created. - name: Look up requested hostname across the cluster community.proxmox.proxmox_vm_info: @@ -64,21 +47,16 @@ register: source_vm no_log: true - - name: Require exactly one source template before reading its configuration - ansible.builtin.assert: - that: - - source_vm.proxmox_vms | length == 1 - fail_msg: "Template {{ vm_template_id }} was missing or ambiguous in the cluster; no VM was created." - - name: Require a cloud-init-ready template on its current node ansible.builtin.assert: that: + - source_vm.proxmox_vms | length == 1 - source_vm.proxmox_vms[0].node is defined - source_vm.proxmox_vms[0].template | bool - source_vm.proxmox_vms[0].config.scsi0 is defined - source_vm.proxmox_vms[0].config.scsi1 is defined - "'cloudinit' in source_vm.proxmox_vms[0].config.scsi1" - fail_msg: "Template {{ vm_template_id }} must be a QEMU template with a node, scsi0 and a scsi1 cloud-init drive; no VM was created." + fail_msg: "Template {{ vm_template_id }} must resolve uniquely to a QEMU template with a node, scsi0 and a scsi1 cloud-init drive; no VM was created." - name: Clone full VM onto requested storage community.proxmox.proxmox_kvm: @@ -97,8 +75,6 @@ that: - cloned_vm.changed - cloned_vm.vmid is defined - - cloned_vm.vmid | string is match('^[0-9]+$') - - cloned_vm.vmid | int >= 100 - cloned_vm.vmid | int != vm_template_id | int fail_msg: >- Clone did not return a valid new VMID (possibly allocated concurrently); @@ -164,10 +140,6 @@ ansible_ssh_timeout: 10 provisioned_vmid: "{{ cloned_vm.vmid }}" - - name: Report guest check start - ansible.builtin.debug: - msg: "VMID {{ cloned_vm.vmid }} started; DNS and SSH port reachable for {{ vm_hostname }}.{{ vm_dns_domains[vm_vlan] }}. Checking guest SSH, cloud-init and Ansible next." - - name: Verify cloud-init and Ansible on the new guest hosts: provisioned_vm gather_facts: false @@ -192,34 +164,17 @@ - "stdout: {{ cloudinit_wait.stdout | trim }}" - "stderr: {{ cloudinit_wait.stderr | trim }}" - - name: Require cloud-init wait to complete - ansible.builtin.assert: - that: cloudinit_wait.rc in [0, 2] - fail_msg: "VMID {{ provisioned_vmid }} cloud-init wait failed (rc {{ cloudinit_wait.rc }}); VM left intact for inspection." - - - name: Read final cloud-init status - ansible.builtin.raw: cloud-init status --long - register: cloudinit_status - changed_when: false - failed_when: false - - - name: Show final cloud-init diagnostics - ansible.builtin.debug: - msg: - - "stdout: {{ cloudinit_status.stdout | trim }}" - - "stderr: {{ cloudinit_status.stderr | trim }}" - - name: Require completed cloud-init ansible.builtin.assert: that: - - cloudinit_status.rc in [0, 2] - - "cloudinit_status.stdout is search('(?m)^status: done\\s*$')" - fail_msg: "VMID {{ provisioned_vmid }} cloud-init status is not complete (rc {{ cloudinit_status.rc }}); VM left intact for inspection." + - cloudinit_wait.rc in [0, 2] + - "cloudinit_wait.stdout is search('(?m)^status: done\\s*$')" + fail_msg: "VMID {{ provisioned_vmid }} cloud-init status is not complete (rc {{ cloudinit_wait.rc }}); VM left intact for inspection." - name: Warn about degraded cloud-init completion ansible.builtin.debug: msg: "VMID {{ provisioned_vmid }} cloud-init completed with degraded status (rc 2); individual cloud-init operations may not have succeeded. Inspect the diagnostics before relying on this guest." - when: cloudinit_wait.rc == 2 or cloudinit_status.rc == 2 + when: cloudinit_wait.rc == 2 - name: Read guest timezone ansible.builtin.command: timedatectl show --property=Timezone --value @@ -232,16 +187,6 @@ become: true when: guest_timezone_before.stdout | trim != vm_timezone - - name: Verify guest timezone - ansible.builtin.command: timedatectl show --property=Timezone --value - register: guest_timezone_after - changed_when: false - - - name: Require configured guest timezone - ansible.builtin.assert: - that: guest_timezone_after.stdout | trim == vm_timezone - fail_msg: "VMID {{ provisioned_vmid }} guest timezone did not become {{ vm_timezone }}; VM left intact for inspection." - - name: Verify final Ansible ping ansible.builtin.ping: -- 2.54.0 From 8e7ac456ce0040558a053bf72dba960f575d7f4b Mon Sep 17 00:00:00 2001 From: Vezpi Date: Mon, 9 Nov 2026 14:24:23 +0000 Subject: [PATCH 12/13] refactor(ansible): reword task names --- ansible/proxmox/provision_vm.yml | 52 ++++++++++---------------------- 1 file changed, 16 insertions(+), 36 deletions(-) diff --git a/ansible/proxmox/provision_vm.yml b/ansible/proxmox/provision_vm.yml index 23d9ed3..ee7519b 100644 --- a/ansible/proxmox/provision_vm.yml +++ b/ansible/proxmox/provision_vm.yml @@ -97,7 +97,7 @@ state: present no_log: true - - name: Grow cloned scsi0 disk to requested size + - name: Resize disk to requested size community.proxmox.proxmox_disk: vmid: "{{ cloned_vm.vmid }}" disk: scsi0 @@ -105,25 +105,21 @@ state: resized no_log: true - - name: Start configured VM + - name: Start VM community.proxmox.proxmox_kvm: vmid: "{{ cloned_vm.vmid }}" state: started no_log: true - name: Wait for guest DNS publication - ansible.builtin.command: - argv: - - getent - - ahosts - - "{{ vm_hostname }}.{{ vm_dns_domains[vm_vlan] }}" + ansible.builtin.command: getent ahosts "{{ vm_hostname }}.{{ vm_dns_domains[vm_vlan] }}" register: guest_dns changed_when: false until: guest_dns.rc == 0 and guest_dns.stdout | length > 0 retries: 30 delay: 5 - - name: Wait for guest SSH port after DNS resolution + - name: Wait for guest SSH port ansible.builtin.wait_for: host: "{{ vm_hostname }}.{{ vm_dns_domains[vm_vlan] }}" port: 22 @@ -131,7 +127,7 @@ timeout: 180 sleep: 5 - - name: Add new guest to ephemeral inventory + - name: Add VM to dynamic inventory ansible.builtin.add_host: name: "{{ vm_hostname }}.{{ vm_dns_domains[vm_vlan] }}" groups: provisioned_vm @@ -146,50 +142,34 @@ vars: vm_timezone: Europe/Paris tasks: - - name: Wait for Ansible connection with Python + - name: Wait for guest to be available ansible.builtin.wait_for_connection: connect_timeout: 10 sleep: 5 timeout: 180 - - name: Wait for cloud-init with an external bound - ansible.builtin.raw: timeout 300 cloud-init status --wait --long + - name: Wait for cloud-init status + ansible.builtin.command: timeout 300 cloud-init status --wait --long register: cloudinit_wait changed_when: false failed_when: false - - - name: Show cloud-init wait diagnostics + + - name: Warn about degraded cloud-init completion ansible.builtin.debug: - msg: - - "stdout: {{ cloudinit_wait.stdout | trim }}" - - "stderr: {{ cloudinit_wait.stderr | trim }}" + msg: "VMID {{ provisioned_vmid }} cloud-init completed with degraded status (rc 2); individual cloud-init operations may not have succeeded. Inspect the diagnostics before relying on this guest." + when: cloudinit_wait.rc == 2 - - name: Require completed cloud-init + - name: Assert cloud-init completion ansible.builtin.assert: that: - cloudinit_wait.rc in [0, 2] - "cloudinit_wait.stdout is search('(?m)^status: done\\s*$')" fail_msg: "VMID {{ provisioned_vmid }} cloud-init status is not complete (rc {{ cloudinit_wait.rc }}); VM left intact for inspection." - - name: Warn about degraded cloud-init completion - ansible.builtin.debug: - msg: "VMID {{ provisioned_vmid }} cloud-init completed with degraded status (rc 2); individual cloud-init operations may not have succeeded. Inspect the diagnostics before relying on this guest." - when: cloudinit_wait.rc == 2 - - - name: Read guest timezone - ansible.builtin.command: timedatectl show --property=Timezone --value - register: guest_timezone_before - changed_when: false - - - name: Set guest display timezone - ansible.builtin.command: - argv: [timedatectl, set-timezone, "{{ vm_timezone }}"] + - name: Set guest timezone + ansible.builtin.command: timedatectl set-timezone "{{ vm_timezone }}" become: true - when: guest_timezone_before.stdout | trim != vm_timezone - - - name: Verify final Ansible ping - ansible.builtin.ping: - name: Report verified guest readiness ansible.builtin.debug: - msg: "VMID {{ provisioned_vmid }} at {{ inventory_hostname }} completed cloud-init and returned Ansible pong." + msg: "VMID {{ provisioned_vmid }} at {{ inventory_hostname }} completed cloud-init." -- 2.54.0 From 61ab7d9b503b466f1d89730296132d3a8d3d8e0b Mon Sep 17 00:00:00 2001 From: Vezpi Date: Mon, 9 Nov 2026 14:41:39 +0000 Subject: [PATCH 13/13] change(ansible): task names --- ansible/proxmox/provision_vm.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ansible/proxmox/provision_vm.yml b/ansible/proxmox/provision_vm.yml index ee7519b..b72a43f 100644 --- a/ansible/proxmox/provision_vm.yml +++ b/ansible/proxmox/provision_vm.yml @@ -58,7 +58,7 @@ - "'cloudinit' in source_vm.proxmox_vms[0].config.scsi1" fail_msg: "Template {{ vm_template_id }} must resolve uniquely to a QEMU template with a node, scsi0 and a scsi1 cloud-init drive; no VM was created." - - name: Clone full VM onto requested storage + - name: Clone template into a new VM community.proxmox.proxmox_kvm: clone: source-template vmid: "{{ vm_template_id }}" @@ -97,7 +97,7 @@ state: present no_log: true - - name: Resize disk to requested size + - name: Resize VM disk to requested size community.proxmox.proxmox_disk: vmid: "{{ cloned_vm.vmid }}" disk: scsi0 -- 2.54.0