Skip to content
Go back

OpenTofu + Proxmox: VMs as Code

By KingPin 17 min read
OpenTofu + Proxmox: VMs as Code
Contents

Your Proxmox VMs Are Snowflakes

You built web01 by hand eight months ago. It has 2 cores, 2 GB of RAM, and a disk size you picked while thinking about lunch. Now you need a second one that matches, and nobody remembers whether the CPU type was host or x86-64-v2-AES. The answer lives in a web UI you have to click through again.

The fix is to declare the VMs in files. OpenTofu reads HCL, compares it to what Proxmox actually has, and shows you a diff before it touches anything. You change memory = 2048 to 4096, run tofu plan, read the diff, run tofu apply. The bpg/proxmox provider turns those files into Proxmox API calls.

Full example: Clone the working files at github.com/KingPin/sumguy-examples/devops/opentofu-proxmox-provider

If you want the template-building side (cloud-init vs Packer), that lives in Proxmox Templates: Cloud-Init vs Packer. This post skips templates entirely and imports a cloud image straight into each VM.

Why OpenTofu, and Which Provider

OpenTofu is the open-source fork of Terraform, created after HashiCorp moved Terraform to the BUSL license. The .tf files are the same HCL, so most Terraform tutorials still apply, though features Terraform added after the fork can differ. The licensing story has its own post: OpenTofu After the Terraform Fork.

Two Proxmox providers show up in every search. Here is how they looked on 2026-12-04, checked through the GitHub API:

bpg/proxmox Telmate/proxmox
Latest release v0.125.1 (2026-12-03) v3.0.2-rc10 (2026-08-30)
Release style Regular tagged releases, still 0.x A long run of release candidates
Proxmox VE 9.x targeted, 8.x supported with limits, 7.x not supported Not stated in its docs

I recommend bpg. The release cadence is steady and the docs track current Proxmox. The catch is the version number: it is 0.x, and the README warns that minor versions can break compatibility. So pin it. The provider docs say OpenTofu 1.6 or newer works but is not exercised in CI, so no test matrix backs that claim. I validated the companion files below with OpenTofu 1.13.11 (init and validate). I have not applied them to a live node.

Proxmox Side: A Token That Can Only Do the Job

Do not hand OpenTofu root@pam and a password. Make a dedicated user and a token. Run this on the Proxmox host:

Terminal window
pveum user add terraform@pve
pveum role add Terraform -privs "VM.Allocate VM.Clone VM.Audit VM.PowerMgmt VM.Config.CPU VM.Config.Memory VM.Config.Disk VM.Config.Network VM.Config.Cloudinit VM.Config.Options VM.Config.HWType VM.Config.CDROM VM.GuestAgent.Audit Datastore.Audit Datastore.AllocateSpace Datastore.AllocateTemplate Sys.Audit Sys.Modify SDN.Use Pool.Audit"
pveum aclmod / -user terraform@pve -role Terraform
pveum user token add terraform@pve provider --privsep=0

The last command prints the token secret once. Copy it. The --privsep=0 flag means the token inherits the user’s permissions. Without it, the token starts with none and you must grant privileges to the token itself.

Treat that privilege list as a starting point. The names target PVE 9: VM.GuestAgent.Audit arrived in PVE 9.0, so on PVE 8 swap it for VM.Monitor, the older privilege that covered guest agent calls. Every name in it comes from the provider docs, and the docs themselves say their own list is “likely too permissive” and that privileges changed in PVE 9.0. I have not proven this exact set is minimal. If an apply returns a 403 naming a privilege, add that one. Also keep SDN.Use or SDN.Audit in the role: the docs say without one of them, PVE hides bridges from the node network list and the provider fails with “interface not found”.

Three limits worth knowing before you hit them:

When You Need SSH

Most of this works through the API alone. The provider needs SSH for uploading snippets (cloud-init user-data files), for some other file uploads, and for importing disks via source_file.path. It does not need SSH for creating VMs, downloading images, or import_from disk imports. Our main example needs none.

If you add SSH while using an API token, set the SSH username in the ssh block, and give the provider an agent or key, because a token has no password to inherit. A non-root SSH user also needs narrow passwordless sudo rules on the node. The provider docs list the exact sudoers lines (pvesm apiinfo, plus tee on the snippets directory) and warn against granting all of qm or pvesm.

Provider Config and State Encryption

Start with versions.tf. It pins the provider and turns on OpenTofu’s native state encryption:

versions.tf
terraform {
required_version = ">= 1.8"
required_providers {
proxmox = {
source = "bpg/proxmox"
version = "~> 0.125.0"
}
}
# Native OpenTofu state encryption. Set TF_VAR_state_passphrase
# (16+ characters) before init. Lose the passphrase, lose the state.
encryption {
key_provider "pbkdf2" "main" {
passphrase = var.state_passphrase
}
method "aes_gcm" "main" {
keys = key_provider.pbkdf2.main
}
state {
method = method.aes_gcm.main
enforced = true
}
plan {
method = method.aes_gcm.main
enforced = true
}
}
}

Why bother? The state file records every VM attribute as plain JSON. A saved plan file (tofu plan -out) also stores your input variables, and the API token sits in it in plaintext. A plaintext state or plan file on a laptop, in a backup, or in a git repo someone pushes by accident is a leak. OpenTofu can encrypt both before they hit disk.

The block derives a key from a passphrase with PBKDF2, then encrypts state and plan files with AES-GCM. enforced = true makes OpenTofu reject any configuration that uses the unencrypted method, so nobody can switch the state or plan back to plaintext by editing the block. Put the passphrase in your password manager. If you lose it, nobody can decrypt that state, including you.

One more migration note: once encryption is configured, OpenTofu refuses to read an existing plaintext state, even with enforced off. For the first apply on an existing project, add method "unencrypted" "migrate" {} and put fallback { method = method.unencrypted.migrate } inside the state and plan blocks. Leave enforced out for that run, because OpenTofu errors when enforced = true and an unencrypted method are both present. After one apply writes the state encrypted, delete the fallback and the unencrypted method, then set enforced = true.

Keep the credentials out of .tf files too. The variables are plain declarations, and the secrets arrive as environment variables:

variables.tf
variable "proxmox_endpoint" {
type = string
description = "Proxmox API URL, for example https://pve.example.lan:8006/"
}
variable "proxmox_api_token" {
type = string
sensitive = true
description = "Full token string: user@realm!tokenid=secret. Set it with TF_VAR_proxmox_api_token."
}
variable "proxmox_insecure" {
type = bool
default = false
description = "Skip TLS verification. Only for a self-signed lab certificate."
}
variable "state_passphrase" {
type = string
sensitive = true
description = "Passphrase for state and plan encryption. Set it with TF_VAR_state_passphrase."
validation {
condition = length(var.state_passphrase) >= 16
error_message = "The passphrase must be at least 16 characters."
}
}
variable "node_name" {
type = string
default = "pve"
}
variable "image_datastore" {
type = string
default = "local"
description = "Datastore that holds the downloaded cloud image. It needs the Import content type enabled."
}
variable "vm_datastore" {
type = string
default = "local-lvm"
description = "Datastore for VM disks and the cloud-init drive."
}
variable "ssh_public_key" {
type = string
description = "Public key injected through cloud-init, for example: ssh-ed25519 AAAA... you@laptop"
}
variable "gateway" {
type = string
default = "192.168.1.1"
}
variable "vms" {
type = map(object({
vm_id = number
cores = number
memory = number
disk_size = number
address = string
}))
description = "One entry per VM. The map key becomes the VM name."
}

Export the two secrets, and keep everything else in a gitignored terraform.tfvars:

Terminal window
export TF_VAR_proxmox_api_token='terraform@pve!provider=xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'
export TF_VAR_state_passphrase='a-long-random-passphrase'

A Cloud Image and One VM

Now main.tf. First the provider and the image download:

main.tf
provider "proxmox" {
endpoint = var.proxmox_endpoint
api_token = var.proxmox_api_token
insecure = var.proxmox_insecure
}
resource "proxmox_download_file" "ubuntu_noble" {
content_type = "import"
datastore_id = var.image_datastore
node_name = var.node_name
url = "https://cloud-images.ubuntu.com/noble/current/noble-server-cloudimg-amd64.img"
# Import content needs a .qcow2, .raw or .vmdk extension, so rename on download.
file_name = "noble-server-cloudimg-amd64.qcow2"
# Do not re-download when Ubuntu publishes a new "current" image.
overwrite = false
}

Use proxmox_download_file. The older name, proxmox_virtual_environment_download_file, is deprecated and goes away in v1.0. The resource asks Proxmox itself to fetch the URL through its download API, so the image never passes through your laptop. There is also an experimental proxmox_vm resource in the docs marked “DO NOT USE”. Ignore it and use proxmox_virtual_environment_vm.

overwrite = false is my choice. By default the provider downloads the file again when the upstream size changes. Existing VMs keep their disks, because import_from only applies at creation. New VMs then boot a newer image than the old ones, and that mismatch surprises people on some random Tuesday. Pin the behavior and update images on purpose.

Now the VM. This is the full resource, already looped over a map:

main.tf
resource "proxmox_virtual_environment_vm" "vm" {
for_each = var.vms
name = each.key
node_name = var.node_name
vm_id = each.value.vm_id
tags = ["opentofu"]
# Cloud images ship without qemu-guest-agent. Leave this false until
# the guest installs and starts it (see the article).
agent {
enabled = false
}
stop_on_destroy = true
cpu {
cores = each.value.cores
type = "x86-64-v2-AES"
}
memory {
dedicated = each.value.memory
}
disk {
datastore_id = var.vm_datastore
import_from = proxmox_download_file.ubuntu_noble.id
interface = "scsi0"
size = each.value.disk_size
}
initialization {
datastore_id = var.vm_datastore
ip_config {
ipv4 {
address = each.value.address
gateway = var.gateway
}
}
user_account {
username = "ubuntu"
keys = [var.ssh_public_key]
}
}
network_device {
bridge = "vmbr0"
}
operating_system {
type = "l26"
}
lifecycle {
prevent_destroy = false # flip to true once a VM holds data you care about
ignore_changes = [tags]
}
}

A few lines deserve a comment:

Stamping Out Three VMs

The map in terraform.tfvars drives everything. Here is the example file:

terraform.tfvars.example
proxmox_endpoint = "https://pve.example.lan:8006/"
proxmox_insecure = true # self-signed certificate
node_name = "pve"
gateway = "192.168.1.1"
ssh_public_key = "ssh-ed25519 AAAA... you@laptop"
vms = {
web01 = { vm_id = 201, cores = 2, memory = 2048, disk_size = 20, address = "192.168.1.51/24" }
web02 = { vm_id = 202, cores = 2, memory = 2048, disk_size = 20, address = "192.168.1.52/24" }
db01 = { vm_id = 203, cores = 4, memory = 4096, disk_size = 40, address = "192.168.1.53/24" }
}

Three lines, three VMs. Adding a fourth is one new line. Removing one deletes it, and tofu plan tells you that before anything happens. Run it:

Terminal window
cp terraform.tfvars.example terraform.tfvars
tofu init
tofu plan
tofu apply

The plan lists the image download and three VM creates. After apply, tofu output ssh_commands prints a login line per VM. The outputs file is short:

outputs.tf
output "vm_ids" {
value = { for name, vm in proxmox_virtual_environment_vm.vm : name => vm.vm_id }
}
output "ssh_commands" {
value = {
for name, cfg in var.vms :
name => "ssh ubuntu@${split("/", cfg.address)[0]}"
}
}

To rebuild one VM from scratch, no clicking:

Terminal window
tofu apply -replace='proxmox_virtual_environment_vm.vm["web01"]'

That destroys web01 and creates it again from the image. The other two stay untouched. This is the payoff: a broken VM is a one-line fix, and a VM you never want to explain is a file you can read.

Gotchas

The Guest Agent Trap

The example sets agent.enabled = false on purpose. Setting it to true tells Proxmox the guest agent is running inside the VM. Ubuntu cloud images do not include it. Per the provider docs, if the agent is not running, shutdown and reboot operations time out and fail, and the failing operation holds a lock on the VM so you cannot even stop it until the timeout passes. The provider also waits for the agent to report an IP, with a default agent.timeout of 15m, on create and on every refresh.

The docs say it plainly: do not run a VM with agent.enabled = true unless the guest starts qemu-guest-agent automatically. The provider cannot tell “not installed” from “slow boot”, so it just waits.

To do it right, install the agent with cloud-init. That needs a snippet, and snippets need SSH, so the provider block gains an ssh block and the datastore needs Snippets enabled. The companion repo ships the optional file as cloud-config-snippet.tf.example:

cloud-config-snippet.tf
resource "proxmox_virtual_environment_file" "cloud_config" {
content_type = "snippets"
datastore_id = var.image_datastore
node_name = var.node_name
source_raw {
file_name = "guest-agent.cloud-config.yaml"
data = <<-EOF2
#cloud-config
users:
- default
- name: ubuntu
groups: sudo
shell: /bin/bash
sudo: ALL=(ALL) NOPASSWD:ALL
ssh_authorized_keys:
- ${var.ssh_public_key}
packages:
- qemu-guest-agent
runcmd:
- systemctl enable --now qemu-guest-agent
EOF2
}
}

Then in the VM resource, set agent { enabled = true }, and inside the initialization block delete user_account and add user_data_file_id = proxmox_virtual_environment_file.cloud_config.id. The role from earlier already includes VM.GuestAgent.Audit, which PVE 9 checks on the agent call the provider uses to read VM IP addresses. I ran tofu validate on that variant and it passes. I did not boot it against a live node.

If a VM is already stuck with the agent flag on and no agent, the docs suggest the Proxmox web UI “Monitor” tab and the system_powerdown command to get it down.

Drift: Someone Clicked in the UI

Someone bumps a VM to 8 GB in the web UI at lunch. The next tofu plan refreshes real state, sees 8 GB against your 2 GB, and proposes to put it back. That is the system working. Read the plan before applying, because the “fix” may reboot the VM.

If the UI change is the one you want, edit the .tf file to match. For attributes you never want OpenTofu to fight over, use ignore_changes. The example does this for tags, and the docs explain why: Proxmox always sorts tags, so an unsorted list in your file shows a permanent diff.

lifecycle {
ignore_changes = [tags]
}

Be sparing. Every attribute in ignore_changes is a place where the file and reality can disagree without anyone knowing.

Plans After Import

Existing VMs can be adopted. The import ID is the node name and VM ID:

Terminal window
tofu import 'proxmox_virtual_environment_vm.vm["web01"]' pve/201

Then run tofu plan. Expect a diff the first time. Import records what exists, and your HCL probably does not describe every setting, so defaults in the schema will want to overwrite values the old VM had. Edit the file until the plan says no changes. Do this before any apply, and read each line.

Destroy Safety

tofu destroy, or a removed map key, deletes the VM and its disks. delete_unreferenced_disks_on_destroy (default true) also removes unused disks, and purge_on_destroy (default true) removes the VM from backup configurations. Two guards help:

For anything with data you cannot rebuild from a cloud image, use both.

The SumGuy Take

Start with one VM. Get the token, the encrypted state, and tofu plan working against a throwaway VM. Then convert the rest as you rebuild them. The first time you replace a broken VM with one command, the web UI starts to feel like a hand tool you reach for only to look around.

Keep the provider pinned, keep the passphrase in a password manager, and treat tofu plan output as something you read, not something you scroll past. OpenTofu will do exactly what the diff says. That is a feature until the day you stop reading it.

Common Questions

Can I use the Telmate Proxmox provider with OpenTofu?

Yes. The OpenTofu registry serves Telmate/proxmox, but its newest 3.x tags are still release candidates (v3.0.2-rc10 as of December 2026). For new work, bpg/proxmox ships regular tagged releases and tracks Proxmox VE 9.x.

Does OpenTofu state encryption protect my Proxmox API token?

Partly. OpenTofu state encryption protects the saved plan file, which is where the token lands: a plan made with tofu plan -out stores every input variable, the API token included. The state file holds VM attributes and does not store the token. Encryption does not hide the token from anyone who can read your shell environment or run tofu with the passphrase, so scope the token narrowly and rotate it.

Can I import existing Proxmox VMs into OpenTofu?

Yes. Write a proxmox_virtual_environment_vm resource, then run tofu import with the node name and VM ID, for example pve/201. Run tofu plan straight afterward and edit your HCL until it shows no changes. Skipping that step lets provider defaults overwrite settings the original VM had, and some of those changes reboot the VM.

Do I need SSH access to the Proxmox node for the bpg/proxmox provider?

No, not for the basics. Creating VMs, downloading images with proxmox_download_file, and importing disks with import_from all use the API. SSH is required for uploading cloud-init snippets, some other file uploads, and source_file.path disk imports. With an API token, you must also set the SSH username in the ssh block.

What happens if I enable the QEMU guest agent but never install it?

The apply stalls. The provider waits for the agent to report data, up to the default agent.timeout of 15 minutes, because it cannot tell a missing agent from a slow boot. Shutdown and reboot also fail until they time out, and the failing operation holds a lock on the VM. Install and start qemu-guest-agent through cloud-init first, or leave the agent disabled.


Wrote about this post on your own site? Send a webmention.

It shows up above once verified.


Next Post
Tailscale Funnel vs Cloudflare Tunnel

Discussion

Powered by Garrul. Sign in with GitHub or Google, or post anonymously.

Related Posts