feat(ansible): provision single VM from Semaphore survey

This commit is contained in:
Hermes Agent committed 2026-11-06 17:43:24 +00:00
1 parent 1325775404
commit 7473233813
5 files changed
+376

No files matched your search

+65
View File
@@ -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.
@@ -0,0 +1,2 @@
proxmoxer>=2.3,<3
requests>=2.31,<3
@@ -0,0 +1,4 @@
---
collections:
- name: community.proxmox
version: "2.0.0"
@@ -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()