Infra revisited

Using Terraform: Getting started

Devops

In this post I’ll provision my first resource on DigitalOcean using Terraform. Most of the post will concern itself with automating my workflow.

Initial project setup

Let’s start with a nice project directory. I prefer to immediately create them on GitHub. There’s really not much to say here.

Some people like to start with intricate folder structures. I usually don’t have a clue where I’ll end up, so I tend not to do this. Instead, everything will be put in the project root initially.

Getting started with DigitalOcean

Then, create an account on DigitalOcean and obtain an access token. For now, just give the access token full permissions – I’ll get back to that later. Be on the safe side though, and add an expiry to the token. Store the token in a file called .env in the project directory:

DIGITALOCEAN_ACCESS_TOKEN=dop_etc_etc_etc

Let’s make sure this token never ends up in Git:

$ echo .env >> .gitignore

Getting started with Terraform

Current best practices suggests to have the following layout for a Terraform project:

my-project/
    provider.tf    # provider specific settings
    main.tf        # top-level entry point for creating resources
    outputs.tf     # file describing all outputs
    variables.tf   # file describing all inputs 

All of these names are conventional. The .tf extension is the only thing required to have Terraform run out of the box.

First, set up the right Terraform providers in provider.tf.

terraform {
  required_providers {
    digitalocean = {
      source  = "digitalocean/digitalocean"
      version = "2.42.0"
    }
  }
}

And initialize:

$ terraform init

Let’s create a new DigitalOcean project using Terraform. Mostly because they are free, so not a lot can go wrong. Let’s set up main.tf

resource "digitalocean_project" "main" {
  name    = "Terraform Cloud-Init Project"
  purpose = "Resources for the Terraform Cloud-Init blogpost"
}

And let’s see if everything is supposed to work:

$ env $(cat .env) terraform plan

Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the following symbols:
  + create

Terraform will perform the following actions:

  # digitalocean_project.main will be created
  + resource "digitalocean_project" "main" {
      + created_at = (known after apply)
      + id         = (known after apply)
      + is_default = false
      + name       = "Terraform Cloud-Init Project"
      + owner_id   = (known after apply)
      + owner_uuid = (known after apply)
      + purpose    = "Resources for the Terraform Cloud-Init blogpost"
      + resources  = (known after apply)
      + updated_at = (known after apply)
    }

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

This looks pretty good. Time to actually create this resource:

$ env $(cat .env) terraform apply -auto-approve

Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the following symbols:
  + create

Terraform will perform the following actions:

  # digitalocean_project.main will be created
  + resource "digitalocean_project" "main" {
      + created_at = (known after apply)
      + id         = (known after apply)
      + is_default = false
      + name       = "Terraform Cloud-Init Project"
      + owner_id   = (known after apply)
      + owner_uuid = (known after apply)
      + purpose    = "Resources for the Terraform Cloud-Init blogpost"
      + resources  = (known after apply)
      + updated_at = (known after apply)
    }

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

Do you want to perform these actions?
  Terraform will perform the actions described above.
  Only 'yes' will be accepted to approve.

  Enter a value: yes

digitalocean_project.main: Creating...
digitalocean_project.main: Creation complete after 3s [id=eaac494a-8471-4dd6-b805-de6d6307df6b]

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

This too looks good. And sure enough, the project shows up on my DigitalOcean panel.

Time to destroy it.

$ env $(cat .env) terraform destroy -auto-approve

The last step is to make sure all the Terraform generated files do not end up in Git, by adding them to .gitignore:

.env
.terraform
.terraform.lock.hcl
terraform.tfstate
terraform.tfstate.backup

And that’s Terraform in a nutshell.

Automate everything

I’m very good at forgetting exact invocations, so I like to put stuff like this in a Makefile:

#!/usr/bin/make
include .env	# make sure the .env variables are present
export			# magic invocation for the above

.PHONY:	help
help:					## Show this help text
	@grep -E -h '\s##\s' $(MAKEFILE_LIST) | awk 'BEGIN {FS= ":.*?## "} {printf "%-20s %s\n", $$1, $$2}'

.PHONY:	clean
clean:					## Clean the current plan file
	rm -f plan.out

.PHONY:	init
init:					## (Re)initialize Terraform providers
	terraform init

.PHONY:	plan
plan:	init plan.out	## Generate the infrastructure plan

plan.out:
	terraform plan -out=$@

.PHONY: check
check:  init            ## Check for configuration drift
	terraform plan -detailed-exitcode

.PHONY: apply
apply:	plan.out		## Apply the plan and create the infrastructure
	terraform apply plan.out

.PHONY:	destroy
destroy:	clean		## Destroy the infrastructure
	terraform destroy -auto-approve

.PHONY:	validate
validate:				## Validate the Terraform files
	terraform fmt
	terraform validate

Yes, this is basically a glorified bash script, but I like it. I stole the make help target from Victoria.

Some typical invocations:

$ make help        # in case I forgot
$ make validate    # this should eventually end up in my pre-commit
$ make clean apply # bring the infrastructure up to date
$ make destroy     # destroy the infrastructure  

Automate even more

I’m a big fan of pre-commit. This tool basically automates the management of pre-commit hooks, doing some basic checks before you can even commit your changes.

The .pre-commit-config.yaml file looks like this:

repos:
  - repo: https://github.com/antonbabenko/pre-commit-terraform
    rev: v1.96.1
    hooks:
      - id: terraform_fmt
      - id: terraform_validate

Run pre-commit install to update the hooks and never commit horrible code again. There are many more pre-commit hooks, but for now this will suffice.