Feat/vm provision ansible #9

Merged
Vezpi merged 13 commits from feat/vm-provision-ansible into main 2026-11-09 15:46:14 +01:00
5 changed files with 376 additions and 0 deletions
Showing only changes of commit 7473233813 - Show all commits

No files matched your search

+133
View File
@@ -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."
+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()