Importing a Hetzner VM into a new Terraform template

I’m creating a new VM on Hetzner that I want to manage with Terraform, but this is the first time I’ve used the Hetzner Provider. Rather than stumble through the required options for a new VM, I used the -generate-config-out option with terraform plan to generate the Terraform config for me based on the currrent config.

Here’s my starting point for my main.tf:

terraform {
  required_providers {
    hcloud = {
      source  = "hetznercloud/hcloud"
      version = "~> 1.45"
    }
  }
}


# Set the variable value in *.tfvars file
# or using the -var="hcloud_token=..." CLI option
variable "hcloud_token" {
  sensitive = true
}

# Configure the Hetzner Cloud Provider
provider "hcloud" {
  token = var.hcloud_token
}

import {
  id = "name-of-my-hertzner-vm"
  to = hcloud_server.name-of-my-new-terraform-resource
}

On running:

terraform plan -generate-config-out=generated.tf

I now have the equivalent Terraform config for my VM, in generated.tf, and now I can include this in my main.tf and manage it incrementally via Terraform from this point onwards.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.