Deploying a Hugo blog to Cloudflare using Terraform

Today I decided I would like to move my blog to Cloudflare Pages. I didn’t want to go with ClickOps, so I created a Terraform configuration.

I started with configuring the Cloudflare Terraform provider.

terraform {
  required_providers {
    cloudflare = {
      source  = "cloudflare/cloudflare"
      version = "3.28.0"
    }
  }
}

provider "cloudflare" {
  api_token = var.api_token
}

Next, I specified the source repository, and deployment config.

I used the HUGO_VERSION environment variable to specify a recent Hugo version, as the default version is quite old.

resource "cloudflare_pages_project" "blog" {
  account_id        = var.account_id
  name              = "mbialon-blog"
  production_branch = "main"

  source {
    type = "github"
    config {
      owner                         = "mbialon"
      repo_name                     = "blog"
      production_branch             = "main"
      pr_comments_enabled           = true
      deployments_enabled           = true
      production_deployment_enabled = true
      preview_branch_includes       = ["*"]
    }
  }

  build_config {
    build_command   = "hugo"
    destination_dir = "public"
  }

  deployment_configs {
    preview {
      environment_variables = {
        HUGO_VERSION = "0.107.0"
      }
    }
    production {
      environment_variables = {
        HUGO_VERSION = "0.107.0"
      }
    }
  }
}

After deploying the site, it received a unique subdomain on *.pages.dev. As I wanted to use my domain, I added the custom domain and specified the DNS record.

resource "cloudflare_pages_domain" "apex" {
  account_id   = var.account_id
  project_name = cloudflare_pages_project.blog.name
  domain       = "bialon.net"
}

resource "cloudflare_record" "apex" {
  zone_id = var.zone_id
  type    = "CNAME"
  name    = "bialon.net"
  value   = cloudflare_pages_project.blog.subdomain
  proxied = true
}

Photo by Andrew Neel on Unsplash