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 | $ mkdir ~/projects/terraform/hetzner |
Create a configuration file:
1 | touch main.tf |
Hezner Configuration
Generate Hetzner Cloud Auth Token:
- Visit https://console.hetzner.cloud/projects, choose a project
- In Security > API TOKENS, click on GENERATE API TOKEN button.
- Enter a name and choose
Read & Write
- Save it for later
Add an ssh key to Hezner Cloud. This key will be used to access your created instance:
1 | $ ssh-keygen -b 2048 -q -t rsa |
Copy the contents of the generated {keyfilename}.pub
:
1 | $ xclip -sel clip ~/.ssh/{keyfilename}.pub |
Paste the key contents into Hezner Cloud:
- In Security > SSH KEYS, click on ADD SSH KEY button
- Paste it in the
SSH Key
section - 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 | .terraform/ |
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 | $ terraform destroy |
If you would like to delete everything without any confirmation prompt, use:
1 | $ terraform destroy -auto-approve |