Terraform is a great tool for automating infrastructure management. You can think of it as infrastructure as code. Well, more like infrastructure as configuration — but you get the idea — you have some configs that spin up servers for you, and configure them the way you want.

Terraform works with a long list of service providers (e.g. AWS, Azure, GCP etc.) and it can be tailored to work with your in-house solutions as well. In this article we're going to go through a simple example of spinning up a droplet on DigitalOcean.

If you don't have a DigitalOcean account yet, sign up using this link — you'll get $50 in credits, I'll get $25; fair deal.

Alright, that's enough of an introduction. Let's get started.

DigitalOcean API token and SSH key

We'll need to generate a token and set up an SSH key before we get started using Terraform, so let's get that out of the way.

Once we're done here, we will have 4 important things that we'll need:

  • API token
  • Path to the private key we generated on your system
  • Path to the public key we generated on your system
  • SSH fingerprint of your key

Log in to DigitalOcean to follow these steps.

Go to the API menu item, and click Generate New Token. Once this screen appears give it a name and press the Generate Token button.

Once your token has been generated, copy it and stash it in a safe place. Your token should look something like this:

72a134d5f2203f5dd58252998bf4823813541b8ac48be03b93e866a2e02072ea

We got the first important thing ✔️

On to the SSH key.

Create an SSH key without a passphrase by typing this command in your terminal

ssh-keygen -t ecdsa

Give it a name when prompted, and specify the directory where you'd like it to be generated.

When it prompts for passphrase hit ENTER twice (no passphrase provided).

You should see something like this in the terminal

Generating public/private ecdsa key pair.
Enter file in which to save the key (C:\some\path\on\your_system): KEY_NAME
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in KEY_NAME.
Your public key has been saved in KEY_NAME.pub.
The key fingerprint is:
SHA256:sIo7STxwxv2ltjAZ1hCVbUyE3G5sKWs3LA9lTZo3Nb9 andrei@DESKTOP-D8GRA4B
The key's randomart image is:
+---[ECDSA 256]---+
|   . BB+         |
|    o.= . o      |
|   . +.O . o     |
|  . = #o= . .    |
|   = X.=S+   .   |
|    O.B +   E    |
|   o.B = .       |
|    o.. .        |
|    oo           |
+----[SHA256]-----+

Save the paths for your private and public key to a text file, we're going to need them.

We got the second and third important things. ✔️

Great, now that we have our SSH keys, copy the content of the public key  (yourkey.pub) you just generated, and head straight back to DigitalOcean.

Find the Security menu item to set up your SSH key, press Add SSH Key, paste the content of your public key in the input and give it a name.

Once you added the SSH key, it should appear under the list of SSH keys in a table showing it's name and it's fingerprint. We need that fingerprint, copy it and stash it somewhere safe.

It should look something like this:

ff:b6:21:cf:e5:1e:0e:9c:6b:7a:a1:00:42:9d:0a:48

The last important thing is stashed. Awesome stuff.  ✔️

Now let's set up Terraform.

Install Terraform

Download the package from here.

You'll download a zip file, which you'll unzip, and it should contain a file named terraform.exe

Copy or move that terraform.exe file in a place you want to keep it e.g.

C:\Users\YOUR_USER\TF

Now grab the path of the directory where you moved it, and append it to your Path environment variable — which you can find by simply typing environment in the windows start search box.

Click on Edit the system environment variables.

Append the directory path to the Path variable.

To test if it worked, restart your command prompt and type this command (it should return the version of Terraform).

terraform -v

Awesome. Terraform should be locked and loaded.

Create a Terraform Project

Now that we got these things out of the way, we can move on to working with Terraform. Let's  start by making a project directory somewhere, and adding two files into it. We'll name one variables.tf and the other one droplet.tf.

The variables.tf file is where all those values that we stashed are going to come into play. You can paste the code below into it, and substitute the placeholders assigned to the default keys with your values.

variable "token" {
    type = "string"
    description = "DigitalOcean API Token"
    default = "YOUR_TOKEN_HERE"
}
variable "public_key" {
    type = "string"
    description = "The Path to Your Public Key"
    default = "PATH_TO_TOUR_PUBLIC_KEY_HERE"
}
variable "private_key" {
    type = "string"
    description = "The Path to Your Private Key"
    default = "PATH_TO_YOUR_PRIVATE_KEY_HERE"
}
variable "ssh_fingerprint" {
    type = "string"
    description = "SSH Key fingerprint"
    default = "YOUR_SSH_FINGERPRINT_HERE"
}

provider "digitalocean" {
    token = "${ var.token }"
}

As you can see we set up DigitalOcean as the provider. You can check the related documentation using this link.

In the droplet.tf file you can paste the code below.

resource "digitalocean_droplet" "tfdroplet" {
    image = "ubuntu-18-04-x64"
    name = "tfdroplet"
    region = "lon1"
    size = "512mb"
    private_networking = true

    ssh_keys = [
        "${var.ssh_fingerprint}"
    ]

    connection {
        user = "root"
        type = "ssh"
        private_key = "${file(var.private_key)}"
        timeout = "2m"
        host = "${self.ipv4_address}"
    }

    provisioner "remote-exec" {
        inline = [
            "export PATH=$PATH:/usr/bin",
            "sudo apt-get update",
            "sudo apt-get -y install nginx"
        ]
    }
}

With the code above we're creating a small DigitalOcean droplet, and configuring it. It is going to run the Ubuntu 18.04 version, it's located in London, and it has a size of 512mb.

After the droplet is created, we're also running an update command and install Nginx to it, to demonstrate how you would go about doing something like this.

Launch 🚀

Alright let's spin up this bad boy. This will be no more than 3 commands.

To install the dependencies needed, let's launch a terminal in your project directory and type:

terraform init

(you can think of this like an npm install, if you're familiar with node)

After terraform has been initialized, we can now run:

terraform plan

This command is going to make an execution plan for you to preview, you should see something like this in your terminal:

Refreshing Terraform state in-memory prior to plan...
The refreshed state will be used to calculate this plan, but will not be
persisted to local or remote state storage.

digitalocean_droplet.tfdroplet: Refreshing state... 

------------------------------------------------------------------------

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:
...
...
...
Plan: 1 to add, 0 to change, 0 to destroy.

Lastly, we can run the apply command to create our droplet and configure it.

terraform apply

This might take a few seconds to complete, but after the installation finishes you'll be able to see your new droplet listed on your DigitalOcean account.

If you want to SSH into it from Putty or your terminal, don't forget to use your private key that we created.

That's about it. I hope you enjoyed this brief look into Terraform and you'll be excited to learn more.