hjs.es CV as PDF
← Projects completed

Declarative Proxmox provisioning with Terraform

LXC containers, Windows VMs and a Kali Linux VM in my Proxmox lab declared in code with Terraform (bpg/proxmox): reusable size profiles, multiple deployments from a single apply, a Windows template with WinRM preconfigured and a Kali image imported straight from the official disk. The apply itself generates the Ansible inventory automatically — from "declared in code" to "ready to configure" without typing a single IP address by hand.

Terraform bpg/proxmox Proxmox VE API Tokens VirtIO WinRM Kali Linux Ansible Git

A project from my personal lab, which is currently paused: this write-up describes how it was built and how it worked.

Context

Every LXC container or VM in this lab — Pi-hole, cloudflared, the Ansible management node, the Windows Server VM itself — started life the same way: by hand from the Proxmox panel, choosing template, resources and network each time. The Ansible project already solved the part about configuring a machine that already exists, but the very existence of the machine — its ID, its resources, its network — was still outside any version control.

Terraform closes that gap: it declares the infrastructure in .tf files versioned in Git, and an apply makes the reality of the cluster match what has been declared. It ran from the same management container that Ansible already used.

Design

01

Provider: bpg/proxmox over Telmate

Telmate is historically the most widely used provider, but it has an open permissions bug (VM.Monitor) on Proxmox VE 9.x. bpg/proxmox is actively maintained, officially supports PVE 9.2 and covers both LXC containers and VMs.

02

Service account and a scoped token

No root@pam. A terraform@pve user with its own least-privilege role (neither PVEAdmin nor an unnecessary Sys.Modify) and an API token separate from any password — if the token were ever leaked, the blast radius is limited to managing VMs and containers, not administering the system. The exact creation commands are in the quick notes.

03

Size profiles + multiple deployment

A flavors map defines reusable profiles (básico/pro/supreme/extreme → cores/RAM/disk), and a for_each over a map of "desired machines" generates as many containers or VMs as are declared in terraform.tfvars with a single apply — no copying and pasting of resource blocks. How that map is filled in is covered in the usage section below.

04

Reusable Windows template

A base VM with VirtIO drivers, qemu-guest-agent and WinRM preconfigured before sysprep — every cloned VM is born ready for Ansible to manage, with no manual steps afterwards. terraform apply clones the template through the clone block of the proxmox_virtual_environment_vm resource.

05

Ansible inventory generated automatically

A locals block builds two clean lists of hostname + IP address: for containers, the declared address (with the /24 stripped); for Windows VMs, the address discovered after creation, read from the ipv4_addresses attribute the resource exposes via the guest agent (filtering out localhost and self-assigned addresses with no DHCP). A templatefile + the hashicorp/local provider write an inventory_generado.ini with [linux]/[windows] already resolved — no IP address is typed by hand at any step.

06

Kali as an imported VM, not cloned from a template

Unlike Windows and the containers, Kali does not come from a template of my own — it is imported directly from the official QEMU image (disk.import_from) with kali/kali credentials already in place. A VM rather than a container was chosen on purpose: the penetration-testing toolset needs raw sockets, Wi-Fi monitor mode and USB access, all of which a container shares (and restricts) at the host kernel level. With no cloud-init in the image, the IP address is set by hand inside the guest after first boot, as with Windows VMs that have no cloud-init template.

07

Power state as a declared field, not a fixed value

At first, started = true was hard-coded in every resource. Powering a machine off by hand in Proxmox did not change what Terraform believed should happen — the next apply switched it back on without saying why. Now started is just another attribute of each entry in contenedores/vms_windows (and kali_started for the single VM), defaulting to true so nothing existing breaks. Really switching something off is now one line in terraform.tfvars, not a recurring fight with Terraform itself.

Usage and variables

Day-to-day work does not touch any .tf file. Everything that changes from one deployment to the next lives in one place: terraform.tfvars. Adding a new machine is one more entry in a map, not a new line of code.

# terraform.tfvars — the only thing you touch to deploy something new

flavors = {
  minimo  = { cores = 1, memory = 512,  disk = 2  }
  basico  = { cores = 1, memory = 1024, disk = 10 }
  pro     = { cores = 2, memory = 2048, disk = 20 }
  supreme = { cores = 3, memory = 3072, disk = 30 }
  extreme = { cores = 4, memory = 4096, disk = 40 }
}

contenedores = {
  ttyd = {
    vm_id    = 103
    hostname = "ttyd"
    flavor   = "minimo"       # 1 core / 512MB / 2GB — plenty for a single binary
    ip       = "192.168.1.14/24"
    gateway  = "192.168.1.1"
  }
}

vms_windows = {
  win_test01 = {
    vm_id          = 490
    name           = "win-test01"
    template_vm_id = 251
  }
}

minimo came about precisely for ttyd: the default flavour (basico, 10 GB) was far more than needed for a container that runs a single binary of a few MB — on a 240 GB SSD shared with Windows VMs and a 90 GB Kali, those 8 GB of difference per machine add up.

The actual workflow, start to finish:

  1. Add (or edit) an entry in contenedores or vms_windows in terraform.tfvars
  2. terraform plan — confirm that Terraform will only create or touch what is expected, nothing more
  3. terraform apply — the machine is created with the declared flavour, template and network
  4. The locals block discovers the real IP address (containers: declared; Windows: via the guest agent) and regenerates inventory_generado.ini
  5. ansible-playbook -i inventory_generado.ini site.yml --limit <machine_name> --ask-vault-pass — the machine ends up configured and hardened

From "one line in a map" to "hardened machine in the inventory" without touching the Proxmox panel or typing an IP address at any intermediate step.

One nuance in that last step, the first time a freshly created machine is provisioned: the user Ansible normally uses does not exist there yet (the playbook itself creates it), so that first contact has to force the user that Terraform did leave authorised — the full detail, with the reasoning, is in the Ansible write-up.

Kali is deliberately left out of this workflow: it is a one-off machine declared directly in its own resource, not a reusable flavour — there is no .tfvars entry to edit to deploy it, just terraform apply once the image has been prepared (see quick notes).

Problems along the way

✗

The token failed with a 403 when cloning: insufficient permissions

terraform apply created the resource but failed midway through the clone operation with 403 Forbidden. The token had general administration privileges but not the specific ones the clone operation requires on the target datastore.

Cause: the role assigned to the service user did not include Datastore.AllocateSpace or Datastore.AllocateTemplate — permissions Proxmox specifically requires when cloning a template and reserving space for the new disk, even though the user could create VMs from scratch.
Solution: extend the custom role with the missing datastore privileges (see the full command in the quick notes) and reassign it — without touching the token, which remains valid.
✗

Parallel clones collided with each other

When several VMs were declared with for_each on the same template, Terraform launched the clones in parallel by default — and the second clone failed with a lock error on the template disk, as if it were already "in use" by another operation.

Cause: Proxmox locks the template for the duration of a clone. Two apply operations trying to clone the same template at once compete for that lock, and the one that arrives second fails instead of waiting.
Solution: limit Terraform's parallelism to one operation at a time when the plan includes new clones (terraform apply -parallelism=1). Slower, but it removes the race condition without having to touch the resource code.
✗

Sysprep failed to generalise: unprovisioned Edge package

When running sysprep /generalize on the Windows template, the process failed with 0x80073cf2. The log (%WINDIR%\System32\Sysprep\Panther\setupact.log) pointed to the exact cause: Package Microsoft.MicrosoftEdge.Stable_... was installed for a user, but not provisioned for all users. It is a known Microsoft bug — Windows Update installs Edge updates "for the current user only" rather than machine-wide, and sysprep requires everything to be provisioned globally before generalising.

Solution: remove the offending package before retrying sysprep:
Get-AppxPackage -AllUsers Microsoft.MicrosoftEdge.Stable | Remove-AppxPackage -AllUsers

If it comes back with a different package, the pattern repeats: look at the log, copy the exact package name and apply the same command with that name.

✗

Renumbering a VM by hand outside Terraform left the state orphaned

A Windows VM managed by Terraform was renumbered directly in Proxmox (qm clone + qm destroy, the same manual procedure used for unmanaged machines). The next terraform plan did not show a clear replacement — the VM appeared as a new creation, with "0 to destroy", as if it had never existed.

Cause: Terraform only persists the result of a refresh on apply, not on plan. The state on disk still pointed to the old VMID, which no longer existed; the plan's internal refresh detected that and discarded it in memory, but without saving the change — hence the contradictory appearance.
Solution: terraform state rm to drop the broken reference, and terraform import pointing at the real VMID (format <node>/<vm_id>). With resources cloned from a template you also need lifecycle { ignore_changes = [clone] } — the clone block cannot be reconstructed from an import, and without ignoring it the next plan tries to re-clone the whole VM from scratch.

A second bug came to light during the import itself: a local that read the guest agent's IP address via ipv4_addresses[0] blew up with Invalid index as soon as the VM was stopped — empty list, index out of range. It was fixed by wrapping the expression in try(..., null).

The most dangerous lesson was in the plan diff itself: Terraform's format is always current state → desired state, and reading it the wrong way round midway through a long session came within one step of applying a hot SCSI controller change to a real Windows VM.

✗

Terraform does not care that you powered a machine off by hand — and -target drags in more than it seems

With started = true fixed in every resource, powering off a VM or container directly in Proxmox had no effect on what Terraform considered correct: the next plan showed it as started: false -> true, switching it back on without warning — the very idea of "declarative" working against you when the desired state never reflected what was actually wanted at that moment.

Cause: the attribute was hard-coded in the resource itself (lxc.tf, vms.tf, kali.tf), not exposed as a variable — there was no way to declare "I want this one off" without editing code each time.
Solution: turn started into an optional(bool, true) field within the type of contenedores and vms_windows, and a separate kali_started variable for the single VM. The desired state now lives in terraform.tfvars, the same place that already manages everything else.

Along the way a second bug surfaced in locals.tf: the try(..., null) that prevented the crash when a Windows VM was off still could not be interpolated inside templatefile() — a null value in a text template blows up just the same, only later. The real fix: separate calculating the IP address from deciding whether the host goes into the inventory, filtering with if v.ip != null before building the file. A machine that is off simply stops appearing in the inventory — which is correct, as there is no IP address for Ansible to connect to.

And a separate trap with terraform apply -target=..., intended for touching a single machine without dragging in the rest: targeting the new container and local_file.ansible_inventory together also switched on a Windows VM that was never named — the inventory depends on reading its IP address via the guest agent, so Terraform pulls in that dependency anyway. Terraform itself warns about it in the plan message ("-target is not for routine use"): it is for a one-off situation, not a substitute for the started field above.

Outcome

The full terraform apply → terraform destroy cycle was tested end to end: containers and Windows VMs are created with their resources and network already declared, the Windows template leaves each VM ready for Ansible with no manual step afterwards, the Kali VM is imported directly from the official image with no intermediate template, and the inventory generates itself after every apply — no IP address is typed by hand at any point. The minimo flavour and the ttyd container were the first real deployment done entirely with this workflow, from nothing to a running machine. Each machine's power state is now a declared field, not a fixed value that Terraform imposes on its own with every apply.

Quick notes

A day-to-day reference, and for rebuilding the Windows template — without having to jump to the repository.

"No changes" in a plan is not always a good sign

terraform plan compares reality with what is already declared, not with what should be — an empty or missing file is not an error to Terraform, it is simply "nothing to do". If a plan returns No changes and you were not expecting it, first check that the file was saved properly (cat main.tf) rather than trusting the result.

Windows template: downloads and preparation

Inside Windows, after installing virtio-win-guest-tools.exe and applying updates — WinRM for Ansible, then generalise:

# WinRM, so that Ansible can manage the VM after deployment
winrm quickconfig -q
winrm set winrm/config/service/auth '@{Basic="true"}'
winrm set winrm/config/service '@{AllowUnencrypted="true"}'
New-NetFirewallRule -Name "WinRM-HTTP-In" -DisplayName "WinRM HTTP" -Enabled True -Direction Inbound -Protocol TCP -LocalPort 5985 -Action Allow -Profile Any

# Generalise and shut down
C:\Windows\System32\Sysprep\sysprep.exe /generalize /oobe /shutdown

Note: AllowUnencrypted="true" + Basic are only acceptable because this template lives inside the lab's isolated LAN — outside that trusted network, the right approach is WinRM over HTTPS with a certificate.

With the VM powered off, convert it into a template from the Proxmox node: qm template <vm_id> (or from the panel: VM → More menu → Convert to template). Once converted, it can no longer be started directly — only cloned.

Linux template (LXC): download, SSH keys and disk

Container templates are different from VM templates: they are downloaded as an image from Proxmox's own repository, not installed by hand.

# List the available templates and download the one you need:
pveam available | grep debian-12
pveam download local debian-12-standard_12.7-1_amd64.tar.zst

# Check that it is now downloaded locally:
pveam list local

Access needs no password and no manual steps: the proxmox_virtual_environment_container resource injects the public SSH key directly in the initialization block, so the container is born reachable by key — ready for Ansible to get in with no intermediate step:

initialization {
  user_account {
    keys = [file("~/.ssh/id_ed25519_terraform.pub")]
  }
}

Growing the disk of an already deployed container (unlike a VM, it is applied live): change disk.size in terraform.tfvars and run terraform apply again — Proxmox resizes the container without stopping it.

Kali image: download, real size and how it is imported

Kali publishes a pre-built QEMU image with kali/kali credentials already in place — no template to generalise. It is downloaded on the Proxmox node itself:

# Extracting the .7z requires p7zip-full
apt install -y p7zip-full
wget https://cdimage.kali.org/kali-2026.2/kali-linux-2026.2-qemu-amd64.7z
7z x kali-linux-2026.2-qemu-amd64.7z

The size reported by qemu-img info is the virtual size, not the space actually used — the qcow2 is sparse ("thin"), and when imported onto LVM-thin storage such as local-lvm it only consumes what Kali actually writes. Even so, that is the number to set as disk.size in Terraform: it cannot be reduced after import, only grown.

qemu-img info kali-linux-2026.2-qemu-amd64.qcow2 | grep "virtual size"

It is moved to the import content type of the local storage (which has to be enabled under Datacenter → Storage → local → Edit → Content) — not to template/iso or directly to local-lvm:

mv kali-linux-2026.2-qemu-amd64.qcow2 /var/lib/vz/import/

And it is referenced in the Terraform resource's disk.import_from using the format <datastore>:import/<file>.qcow2 — Proxmox converts the qcow2 to raw automatically when importing it onto LVM storage.

With no cloud-init in the image, the VM comes up on DHCP at first boot. A static IP address is set inside the guest itself:

# confirm the real name of the connection before touching anything
nmcli con show
nmcli con mod "<name>" ipv4.addresses 192.168.1.60/24 ipv4.gateway 192.168.1.1 ipv4.dns 8.8.8.8 ipv4.method manual
nmcli con up "<name>"
Basic Terraform commands
terraform init      # downloads providers
terraform plan      # simulates, touches nothing
terraform apply     # applies what is declared
terraform destroy   # removes what the state manages
terraform validate  # checks syntax only
terraform state list           # what is in the state
Proxmox user and token (pveum)

A least-privilege role for the service user — neither PVEAdmin nor system access, only what Terraform needs to create, clone and manage VMs and containers (it includes the datastore permissions that were missing in the problem above):

# Create the least-privilege role:
pveum role add TerraformProv -privs "VM.Allocate,VM.Clone,VM.Config.Disk,VM.Config.CPU,VM.Config.Memory,VM.Config.Network,VM.Config.Options,VM.Config.Cloudinit,VM.Monitor,VM.Audit,VM.PowerMgmt,Datastore.AllocateSpace,Datastore.AllocateTemplate,Datastore.Audit,Pool.Allocate,SDN.Use"

# Create the service user and assign it the role:
pveum user add terraform@pve
pveum aclmod / -user terraform@pve -role TerraformProv

# Generate the API token (independent of any password):
pveum user token add terraform@pve terraform-token --privsep=0
pveum user token list terraform@pve
pveum user token remove terraform@pve terraform-token   # to rotate it
Automatically generated Ansible inventory

After every apply, the file is written to the root of the repository (gitignored — it contains real addresses from the network):

cat inventory_generado.ini

# Use it directly with Ansible:
ansible-playbook -i inventory_generado.ini site.yml --limit linux
ansible-playbook -i inventory_generado.ini site.yml --limit windows --ask-vault-pass

If the [windows] section comes out empty or with a 169.254.x.x address, the guest agent had not resolved the real address in time — check with qm agent <id> network-get-interfaces and run terraform apply again (idempotent, it only regenerates the file).

Recover a resource whose VMID changed outside Terraform

If a VM or container managed by Terraform is renumbered by hand in Proxmox (rather than through Terraform itself), the state is left pointing at an ID that no longer exists. A normal terraform plan does not make this clear — it may show the resource as a new creation rather than a replacement. To reconcile it:

# 1. Drop the broken reference (touches nothing in Proxmox, only the state)
terraform state rm 'proxmox_virtual_environment_vm.<resource>["<key>"]'

# 2. Update the vm_id in terraform.tfvars to the real value

# 3. Import it under the correct address
terraform import 'proxmox_virtual_environment_vm.<resource>["<key>"]' <node>/<real_vm_id>

# 4. ALWAYS review the plan carefully before applying
terraform plan

If the resource was originally created with a clone block, add lifecycle { ignore_changes = [clone] } before importing — that block cannot be reconstructed from the import, and without ignoring it the plan tries to re-clone the whole machine from scratch, losing everything it had inside.

Before publishing: check there are no secrets in the Git history

A clean file in the current commit guarantees nothing — if the secret was pushed and then deleted in a later commit, it can still be downloaded by anyone who runs git clone and looks at the history. .gitignore only prevents future uploads, it does not clean up what has already been committed:

# Did the real .tfvars get committed before the .gitignore existed?
git log --all --full-history -- terraform.tfvars

# Does the real token value appear anywhere in the history?
git log -p --all | grep -i "terraform-token="

If anything shows up: purge it from the history with git-filter-repo (not filter-branch, which is obsolete) and rotate the credential anyway — purging cleans the repository, it does not undo a copy that may already have been made while it was public.

View the code

The repository is public:

Looking for someone to join your systems team?

CV as PDFhugo@hjs.es