Cloudflare DNS Terraform Cloud

What

Why

  • Codify all the things / IaC
  • Remote state management in Terraform Cloud
  • No more manual DNS udpates

How

High-level summary - the Terraform config containing DNS zone record definitions will live in a GitHub repo. On pushes to the main branch, a GitHub Action, using the hashicorp/setup-terraform action, will run the Terraform config in an API/CLI driven workspace on Terraform Cloud, and update Cloudflare.

Prerequisites:

Steps:

  • Create new GitHub repo, fork or use as example clayshek/cloudflare-dns-terraform-cloud. This uses the Cloudflare provider
  • Create new Terraform Cloud Workspace, of type API-driven workflow
  • In Terraform Cloud, create a new Token for GitHub Actions to use
  • Add a new Actions Secret to your GitHub repo, named TF_API_TOKEN, for the token created in prior step
  • In Cloudflare, create an API token, using “Edit zone DNS” token template, to enable updating the zone in scope
  • Add a new Actions Secret to your GitHub repo, named CLOUDFLARE_API_TOKEN for the token created in prior step
  • If all is setup correctly, updates to the repo’s main branch should start an Action initiated run in Terraform Cloud

Note:

An alternative approach to the above would be a VCS integrated TF Cloud Workspace. Under this model, the GitHub Actions component would not be required. TF Cloud would monitor the repo for changes, and run terraform plan/apply directly in the TF Cloud Workspace. This would require some minor TF config updates, and adding an environment variable to the TF Cloud Workspace for CLOUDFLARE_API_TOKEN instead of as a GitHub secret. Personally prefer the API driven workspace, enabling all config, including API token secret, to live in GitHub.

References:

Written on January 27, 2022