Terraform Example With Hetzner

This article shows how to use Terraform to create a single VPS instance using the European Hetzner cloud provider.

Setup

If you have not installed Terraform yet, download and install it following any of the options listed here

Prepare a terraform folder:

1
2
$ mkdir ~/projects/terraform/hetzner
$ cd ~/projects/terraform/hetzner

Create a configuration file:

1
touch main.tf

Hezner Configuration

Generate Hetzner Cloud Auth Token:

  1. Visit https://console.hetzner.cloud/projects, choose a project
  2. In Security > API TOKENS, click on GENERATE API TOKEN button.
  3. Enter a name and choose Read & Write
  4. Save it for later

Add an ssh key to Hezner Cloud. This key will be used to access your created instance:

1
2
$ ssh-keygen -b 2048 -q -t rsa
# Enter a keyfilename for the key file when prompted

Copy the contents of the generated {keyfilename}.pub:

1
$ xclip -sel clip ~/.ssh/{keyfilename}.pub

Paste the key contents into Hezner Cloud:

  1. In Security > SSH KEYS, click on ADD SSH KEY button
  2. Paste it in the SSH Key section
  3. Click on ADD

After adding the key, a key fingerprint is generated. Fingerprint looks like:

1
de:c7:80:23:5b:3e:28:52:1a:5d:0f:84:1b:fe:38:ec.

Save it for later.

Main Terraform File

Copy the contents of the following gist, paste it into the main.tf file and update AUTH_TOKEN and SSH_KEY_FINGERPRINT values:

Initialize a terraform working directory:

1
$ terraform init

The Hetzner provider will be downloaded by terraform into the .terraform folder:

1
$ tree .terraform/

The following components are downloaded from the terraform registry:

1
2
3
4
5
6
7
8
9
10
11
12
.terraform/
└── plugins
├── registry.terraform.io
│   └── hetznercloud
│   └── hcloud
│   └── 1.24.0
│   └── darwin_amd64
│   ├── CHANGELOG.md
│   ├── LICENSE
│   ├── README.md
│   └── terraform-provider-hcloud_v1.24.0
└── selections.json

In order to run the project and create the server instance, run the command:

1
$ terraform apply

In the command output, you could find the ip address of the newly created server:

1
server_ip_ubuntu18 = 135.181.158.228

Access the instance

Use the printed ip address to ssh into the instace:

1
$ ssh -i ~/.ssh/{keyfilename}.pub root@135.181.158.228

Delete Everything

To delete or destroy the infrastrucutre managed by terraform, run:

1
2
$ terraform destroy
# type yes when prompted

If you would like to delete everything without any confirmation prompt, use:

1
$ terraform destroy -auto-approve