Cloudflare + Terraform DNS Records

I use Cloudflare as a CDN everywhere I can via multiple domains for the different obsessions of mine.

The Cloudflare web-based GUI is intuitive and very easy to manage though I really hate manual entry of things, web-based or not. I like automation.

Also: I love Terraform.

Cloudflare and Terraform together make life so much easier.

I have written a couple of modules but for this post I am only referring to Cloudflare DNS Record Module.

This module can create Cloudflare DNS records of the following type:

    A – IPv4 address

      proxy == true
      proxy == false

    AAAA – IPv6 address

      proxy == true
      proxy == false

    CNAME – Canonical name

      proxy == true
      proxy == false

    SPF – Sender Policy Framework
    TXT – Text record

Later versions of this module will also allow for MX, NS, SRV, and CAA records.

Here’s a very basic example of the module to create A and AAAA records through Cloudflare’s network:

That looks easy. It is not very maintainable.

Let’s do this again but this time let’s use a vars file to allow for easier maintenance!

Let’s start with my file:

And our new Terraform file:

Why is this easier? Because now, with a bit of effort on state storage, you can support each domain in a consistent fashion within Cloudflare by using Terraform and multiple vars files. I would suggest looking into using Terraform Workspaces with durable storage using S3.

Using a workspace set up you can do fun things using a S3 backend for the state file yet continue to keep good separation between your different domains.

Here’s a quick example script that forces the issue and I even left something for you, the reader, to finish.

Leave a Reply