Automating My Site Infrastructure with Terraform

I just reworked my personal site to automate nearly all of its setup in terraform (with some help from GPT Luna), and thought I'd blog a bit about how it works.

Define services and variables

For a simple site like michaelborn.me, there are just a few services I needed:

  • Cloudflare (domain registration and DNS management)
  • Netlify (static site hosting)
  • Uptime Robot (uptime monitors)

Later, I'd like to add sentry.io... but we'll leave that for another day. 🙂

For each of these I needed to grab an API key or token from my account settings, as well as a few other details. Note that neither Cloudflare domain registration nor Netlify site setup are programmable at this time, so you'll need to set those up through the UI before continuing.

Once I had the api keys/tokens and a few other details, I recorded them in a vcs-ignored .tfvars file:

# terraform.tfvars
domain = "michaelborn.me"

netlify_site_name = "mysitename"
netlify_team_slug = "myteamslug"

cloudflare_account_id = "xyz_123"
cloudflare_api_token = "cloudflare_api_token_here"

netlify_api_token    = "netlify_api_token_here"
uptimerobot_api_key  = "uptime_robot_api_key"

For anyone following along, it it is HIGHLY important you ignore this file from your VCS of choice!

echo 'terraform.tfvars' >> .gitignore

After defining the various api keys and secrets, I then created main.tf to define the basic providers I'll be working with, and the terraform provider versions:

terraform {
  required_version = ">= 1.8"

  required_providers {
    cloudflare = {
      source  = "cloudflare/cloudflare"
      version = "~> 5.0"
    }
    netlify = {
      source  = "netlify/netlify"
      version = "~> 0.4.0"
    }
    uptimerobot = {
      source  = "uptimerobot/uptimerobot"
      version = "~> 1.15"
    }
  }
}

Then I configured each provider with their api keys:

provider "cloudflare" {
  api_token = var.cloudflare_api_token
}

provider "netlify" {
  token             = var.netlify_api_token
  default_team_slug = var.netlify_team_slug
}

provider "uptimerobot" {
  api_key = var.uptimerobot_api_key
}

Domain Registration

Next I needed to set up the cloudflare zone for my domain. Again, this requires some cloudflare information in our terraform.tfvars file:

cloudflare_account_id = "xyz_123"
cloudflare_api_token = "cloudflare_api_token_here"

Once we have the cloudflare account authenticated, we can define the cloudflare "zone" for this domain by creating a new cloudflare.tf file:

resource "cloudflare_zone" "main" {
  account = {
    id = var.cloudflare_account_id
  }
  name = var.domain
  type = "full"

  lifecycle {
    prevent_destroy = true
  }
}

I purposely set lifecycle.prevent_destroy = true to prevent terraform from ever destroying (or creating a plan to destroy) this zone. Doing so would be a bit catastrophic for my site, obviously. For my purposes, I consider domain names write-once. 🙂

I actually transferred my domain from Namecheap to Cloudflare during this process for reasons that I'll blog about later. When I completed the migration, I discovered that Cloudflare's terraform provider no longer supports domain creation! Not that it matters for existing sites, but it's worth knowing that for new projects you'll be required to use the UI to purchase the domain and do the initial setup. See this feature request for more info.

DNS Records

Next, I needed to record the existing DNS records I have for michaelborn.me, and point it at the Netlify load balancer.

For each of these, I simply needed to add a cloudflare_dns_record resource, name it, and add the block to my cloudflare.tf file:

resource "cloudflare_dns_record" "apex" {
  zone_id = cloudflare_zone.main.id
  name    = var.domain
  content = "apex-loadbalancer.netlify.com"
  type    = "CNAME"
  ttl     = 1     # 1 = "auto"; Cloudflare manages it
  proxied = true  # orange cloud: TLS terminates at Cloudflare's edge
}

I used GPT Luna heavily for this portion by copy/pasting DNS records from my cloudflare DNS dashboard. This saved me a ton of time over manually editing these dns record configs, but please note that terraform allows generating resource config via terraform plan -generate-config-out="generated_resources.tf".

For the www version, I'll just CNAME that to the root michaelborn.me:

resource "cloudflare_dns_record" "www" {
  zone_id = cloudflare_zone.main.id
  name    = local.www_hostname
  content = var.domain
  type    = "CNAME"
  ttl     = 1
  proxied = true
}

The ttl=1 tells Cloudflare to use automatic dns expiry. I know it looks like 1 second, but it's not. 😀

Netlify Hosting

Netlify's terraform support is admittedly pretty weak. You cannot create Netlify projects using terraform, so if you're following this guide you'll have to manually create the netlify site/project in the netlify dashboard, then grab the site name and copy it into terraform.tfvars:

netlify_site_name = "michaelbornme-nuxt"
netlify_team_slug = "michaelborn"

Once I had an existing project and those vars configured in our variable file, I was able to declare the netlify site:

data "netlify_site" "main" {
  name = var.netlify_site_name
}

Just to repeat: this does basically nothing besides document the setup. Netlify does not allow writes to the site from terraform!

Here's where we can actually declare and define some modifiable config - the domain settings for this site:

resource "netlify_site_domain_settings" "main" {
  site_id        = data.netlify_site.main.id
  custom_domain  = "www.${var.domain}"
  domain_aliases = []
}

This tells Netlify to use www.michaelborn.me as the primary domain.

I could have used this section for a redirect from michaelborn.me -> www.michaelborn.me, buuuut I already handle that via my netlify.toml config file:

[[redirects]]
from = "https://michaelborn.me/*"
to = "https://www.michaelborn.me/:splat"
status = 301

Uptime Robot

The last service I set up with terraform was an uptime monitor courtesy of Uptime Robot's generous free plan. (For my personal site, a 5 minute monitor is fine. For client projects, you'll probably want a 60s check.)

This one's pretty straightforward. We define an uptimerobot_monitor resource for michaelborn.me, give it the url to hit and an interval to use, then set a 30 second timeout.

resource "uptimerobot_monitor" "www" {
  name     = var.domain
  type     = "HTTP"
  url      = "https://www.${var.domain}"
  interval = 300
  timeout  = 30

  check_ssl_errors    = true
  follow_redirections = true
}

Validate On Push

Before calling this "done", I wanted to know my terraform config was valid on each new build. I achieved that via a simple github actions workflow which runs on push any time a file under infra/ is changed:

on:
  push:
    branches: [main]
    paths:
      - "infra/**"
  pull_request:
    branches: [main]
    paths:
      - "infra/**"

If one of those changes is detected, a simple validate job clones the repo and runs terraform validate on the infra directory:

- name: terraform validate
  uses: dflook/terraform-validate@v2
  with:
    path: infra

The entire workflow looks like this:

name: Terraform Validate

on:
  push:
    branches: [main]
    paths:
      - "infra/**"
  pull_request:
    branches: [main]
    paths:
      - "infra/**"

jobs:
  validate:
    name: Validate Terraform config
    runs-on: ubuntu-latest
    steps:
      - name: Checkout
        uses: actions/checkout@v7

      - name: terraform validate
        uses: dflook/terraform-validate@v2
        with:
          path: infra

I quickly tested this by adding a space in terraform {...} immediately breaking my main.tf file. Here's what that failure looks like:

example of broken terraform config causing a build failure. Image shows 'Error: Unsupported block type... Blocks of type "terraf" are not expected here.'

Conclusion

This is a simple terraform setup for a simple personal site. Terraform becomes a lot more useful when working with AWS, Azure, or other cloud hosting providers that "treat servers like cattle". My one gripe is that much of this setup (cloudflare and netlify) still requires manual UI work. Well, what are you going to do? I'm still happy with the result!

Note that I used GPT Luna heavily to create the initial terraform config, so I can't take all the credit for this. I've adjusted it to my liking, and have simplified my setup a bit for this post.