Logo GhassenBLOG
Provisioning a VPS in Hetzner using Terraform

Provisioning a VPS in Hetzner using Terraform

Ghassen Ouertani Ghassen Ouertani
February 24, 2025
3 min read
Table of Contents

Provisioning a VPS in Hetzner using Terraform

Introduction

Hetzner Cloud is a cost-effective cloud provider offering high-performance VPS instances. Using Terraform, we can automate VPS provisioning, making it easy to manage infrastructure as code.

Benefits of Using Terraform for Hetzner VPS

  • Infrastructure as Code: Manage your cloud infrastructure in a declarative manner.
  • Automation: Quickly create and destroy servers as needed.
  • Version Control: Track infrastructure changes using Git.
  • Scalability: Easily scale resources up or down.

Prerequisites

Before proceeding, ensure you have:

  • A Hetzner Cloud account
  • Terraform installed (terraform CLI)
  • An SSH key for secure access

Step-by-Step Guide

1. Generate a Hetzner API Token

  1. Log in to your Hetzner Cloud Console.
  2. Navigate to Security > API Tokens.
  3. Click Generate API Token.
  4. Name your token (e.g., terraform-access) and set appropriate permissions.
  5. Copy and store the token securely.

2. Create an SSH Key Pair

Run the following command to generate an SSH key (if you don’t have one):

ssh-keygen -t rsa -b 4096 -C "your-email@example.com"

Upload the public key to Hetzner Cloud under SSH Keys.

3. Install Terraform

Download and install Terraform:

# macOS
brew install terraform
 
# Linux
wget https://releases.hashicorp.com/terraform/X.Y.Z/terraform_X.Y.Z_linux_amd64.zip
unzip terraform_X.Y.Z_linux_amd64.zip
sudo mv terraform /usr/local/bin/

Verify installation:

terraform version

4. Create a Terraform Configuration File

Create a new directory and main.tf file:

mkdir hetzner-terraform && cd hetzner-terraform
nano main.tf

Add the following Terraform configuration:

provider "hcloud" {
  token = var.hcloud_token
}
 
variable "hcloud_token" {}
 
resource "hcloud_server" "my_vps" {
  name        = "my-vps"
  image       = "ubuntu-22.04"
  server_type = "cx21"
  location    = "nbg1"
  ssh_keys    = ["my-ssh-key"]
}

5. Initialize and Apply Terraform

  1. Initialize Terraform:

    terraform init
  2. Create a terraform.tfvars file to store the Hetzner API token:

    echo 'hcloud_token = "your-hetzner-api-token"' > terraform.tfvars
  3. Apply the configuration:

    terraform apply

    Type yes when prompted to confirm.

6. Connect to the VPS

Once the server is created, find its IP:

terraform output

Then, connect using SSH:

ssh root@<your-vps-ip>

7. Destroy the VPS (Optional)

To remove the VPS when it’s no longer needed:

terraform destroy

Conclusion

Using Terraform, you can easily automate the provisioning of a Hetzner VPS, ensuring a repeatable and scalable infrastructure setup. Happy coding! 🚀


Have questions? Drop them below! 🎯