How to create a vm on proxmox using terraform

Posted by Arun Tomar on 25 November 2023

How to create a vm on proxmox using terraform

Github Repo This is the github repo that has the code https://github.com/aruntomar/homelab/tree/main/proxmox/proxmox_vm

Steps

We are going to use this terraform provider, as there is no official version. https://registry.terraform.io/providers/Telmate/proxmox/latest

Step 1

Create the role and permissions as described on this link and then create the credentials. I prefer to use api tokens rather than username, password. And i also like to use environment variables.

https://registry.terraform.io/providers/Telmate/proxmox/latest/docs

Step 2

Add terraform provider and configure api url

provider.tf

terraform {
  required_providers {
    proxmox = {
      source  = "Telmate/proxmox"
      version = "2.9.14"
    }
  }
}

provider "proxmox" {
  # Configuration options
  pm_api_url = "https://<proxmox server ip address>:8006/api2/json"
}

Step 3

Create vm using proxmox_vm_qemu resource.

main.tf

resource "proxmox_vm_qemu" "vm" {
  name        = "vm1"
  desc        = "vm created by terraform"
  target_node = "<name of your proxmox server in the datacenter>"

  # name of the template to clone. I have another blog post to create a template. 
  clone = "debian-bookworm-template"

  disk {
    type    = "virtio"
    storage = "local-lvm"
    size    = "10G"
  }

  network {
    model  = "virtio"
    bridge = "vmbr0"
  }
  cores   = 2
  sockets = 1
  memory  = 1024

  ssh_user   = "<default username of your cloud image>"
  os_type    = "cloud-init"
  ipconfig0  = "ip=<static ip>,gw=<gateway>"
  nameserver = "<dns server>"

  sshkeys = <<EOF
<your public ssh keys>
EOF

  connection {
    type = "ssh"
    user = self.ssh_user
    host = "<static ip>"
    port = 22
  }

  provisioner "remote-exec" {
    inline = [
      "ip a"
    ]
  }
}

Step 4

$ terraform init
$ terraform plan
$ terraform apply