Get Rewarded! We will reward you with up to €50 credit on your account for every tutorial that you write and we publish!

How-to: Hetzner Cloud Terraform Provider

profile picture
Author
Lukas Kämmerling
Published
2019-03-11
Time to read
7 minutes reading time

Introduction

In this how-to you will learn to use the hcloud Terraform provider. This includes how to create and delete resources and how to do more complex scenarios like attaching a volume to a server.

Prerequisites

  • Basic knowledge about the Hetzner Cloud
  • Hetzner Cloud API token
  • Terraform is installed and you have basic knowledge about it

You can find general information about Hetzner Cloud server types, images and volumes in the Hetzner Docs.

In order to create a Hetzner Cloud API token, please visit Hetzner Cloud Console at https://console.hetzner.cloud, select your project, click "Access" on the left menu, switch to "API TOKENS" tab, click "GENERATE API TOKEN" button and follow the token creation master.

Step 1 - Basic Usage

First of all, we create a new directory which will contain our Terraform configuration. We will call it terraform and create two new files called hcloud.tf and variables.tf. You can name the files as you like.

mkdir terraform
touch hcloud.tf
touch variables.tf

You can now edit the hcloud.tf with a text editor of your choice.

You can find the complete documentation about the Terraform provider in the Terraform documentation.

We will first copy the Example Usage from the documentation.

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

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

# Create a server
resource "hcloud_server" "web" {
  # ...
}

We will see, what the specific parts mean:

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

We simply tell Terraform, that we will give it a variable called hcloud_token. You can specify the value of this variable by using a CLI option or by using a terraform.tfvars file. In this tutorial, we will use the config.tfvars-file. This file will contain our token.

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

We tell Terraform, that we want to use the provider hcloud. Terraform will download the latest version of the provider plugin on terraform init. We also configure the hcloud provider plugin with the variable hcloud_token.

# Create a server
resource "hcloud_server" "web" {
  # ...
}

This short snippet does basically nothing. It just defines a resource from type hcloud_server called web. But it won't work, because we didn't tell Terraform which server should be created.

You can now edit the variables.tf with a text editor of your choice.

We will first copy the following example into the file.

terraform {
  required_providers {
    hcloud = {
      source = "hetznercloud/hcloud"
    }
  }
  required_version = ">= 0.13"
}

We will see, what the specific parts mean:

required_providers {
    hcloud = {
      source = "hetznercloud/hcloud"
    }
}

Each Terraform module must declare which providers it requires, so that Terraform can install and use them. Provider requirements are declared in a required_providers block. A provider requirement consists of a local name (hcloud), a source location (hetznercloud/hcloud) , and a version constraint. In our case, we only add the source which forces terraform to use the latest provider version.

  required_version = ">= 0.13"

The required_version setting accepts a version constraint string, which specifies which versions of Terraform can be used with your configuration. in our case, we use v0.13 or higher.

So now you should create a terraform.tfvars -file which will contain the following content:

hcloud_token = "YOUR_API_TOKEN"

After this we will run terraform init. You should get a similar response to that below:

* provider.hcloud: version = "~> 1.8"

Terraform has been successfully initialized!

Congratulations! You have successfully installed the hcloud provider plugin!

Step 2 - Create a server

You have now a basic overview of the hcloud Terraform provider, but of course, you want a more detailed view. So let's create a server.

We open our hcloud.tf file and go to the resource "hcloud_server" "web" section. We will replace it with the following snippet:

# Create a server
resource "hcloud_server" "web" {
  name        = "my-server"
  image       = "ubuntu-18.04"
  server_type = "cx11"
}

This will create a new server with the name my-server, the image ubuntu-18.04 and the server type cx11. When you now run terraform apply and confirm the message by typing yes ENTER, you should see a freshly created CX11 server in the Hetzner Cloud Console! You should get a similar response like below:

hcloud_server.web: Creating...
  backup_window: "" => "<computed>"
  backups:       "" => "false"
  datacenter:    "" => "<computed>"
  image:         "" => "ubuntu-18.04"
  ipv4_address:  "" => "<computed>"
  ipv6_address:  "" => "<computed>"
  ipv6_network:  "" => "<computed>"
  keep_disk:     "" => "false"
  location:      "" => "<computed>"
  name:          "" => "my-server"
  server_type:   "" => "cx11"
  status:        "" => "<computed>"
hcloud_server.web: Still creating... (10s elapsed)
hcloud_server.web: Still creating... (20s elapsed)
hcloud_server.web: Still creating... (30s elapsed)
hcloud_server.web: Creation complete after 30s (ID: 2035350)

Apply complete! Resources: 1 added, 0 changed, 0 destroyed.

Cool! You created your first Hetzner Cloud server with Terraform! You can now run terraform destroy and confirm this too, to remove the server. You should get a response similar to this:

hcloud_server.web: Refreshing state... (ID: 2035350)

An execution plan has been generated and is shown below.
Resource actions are indicated with the following symbols:
  - destroy

Terraform will perform the following actions:

  - hcloud_server.web

Plan: 0 to add, 0 to change, 1 to destroy.

Do you really want to destroy all resources?
  Terraform will destroy all your managed infrastructure, as shown above.
  There is no undo. Only 'yes' will be accepted to confirm.

  Enter a value: yes

hcloud_server.web: Destroying... (ID: 2035350)
hcloud_server.web: Destruction complete after 0s

Destroy complete! Resources: 1 destroyed.

Step 3 - Create a volume and attach it to a server

You now have learned how to create a resource. Now I want to show you how easily you can create a bunch of resources and combine them. We will use a basic CX11 server and a volume in this step.

First of all, you should open your hcloud.tf file in an editor of your choice.

You should see something like this:

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

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

# Create a server
resource "hcloud_server" "web" {
  name        = "my-server"
  image       = "ubuntu-18.04"
  server_type = "cx11"
}

Now we want to add a volume to this section, so we need to add a new resource block:

# Create a volume
resource "hcloud_volume" "storage" {
  name       = "my-volume"
  size       = 50
  server_id  = "${hcloud_server.web.id}"
  automount  = true
  format     = "ext4"
}

This short snipped will create a new volume called my-volume with a size of 50 GB and format it as ext4. It will automatically mount the volume on the server. We specified too, that it should be attached to the server "${hcloud_server.web.id}", which will result in the ID of our server my-server.

When you now run terraform plan, you should see a similar response like below:

An execution plan has been generated and is shown below.
Resource actions are indicated with the following symbols:
  + create

Terraform will perform the following actions:

  + hcloud_server.web
      id:            <computed>
      backup_window: <computed>
      backups:       "false"
      datacenter:    <computed>
      image:         "ubuntu-18.04"
      ipv4_address:  <computed>
      ipv6_address:  <computed>
      ipv6_network:  <computed>
      keep_disk:     "false"
      location:      <computed>
      name:          "my-server"
      server_type:   "cx11"
      status:        <computed>

  + hcloud_volume.volume
      id:            <computed>
      automount:     "true"
      linux_device:  <computed>
      location:      <computed>
      name:          "my-volume"
      server_id:     "0"
      size:          "50"


Plan: 2 to add, 0 to change, 0 to destroy.

When you now run terraform apply to apply those changes, you can see a volume with 50 GB storage. This is attached to your server in the Hetzner Cloud Console.

Conclusion

You now have a basic overview of the Hetzner Cloud Terraform Provider. We have covered how you can create and delete resources and how to do more complex scenarios like attaching a volume to a server. You can find more help on the official documentation. If you need deeper help, just open an issue on our Github Repository.

Want to contribute?

Get Rewarded: Get up to €50 in credit! Be a part of the community and contribute. Do it for the money. Do it for the bragging rights. And do it to teach others!

Report Issue
Try Hetzner Cloud

Get €20/$20 free credit!

Valid until: 31 December 2024 Valid for: 3 months and only for new customers
Get started
Want to contribute?

Get Rewarded: Get up to €50 credit on your account for every tutorial you write and we publish!

Find out more