Cloudflare + Terraform DNS Records (Updated: 20181226)

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.

I also 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 maintain Cloudflare DNS records and has been tested on the following types:

    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
    MX – Mail Exchange records
    NS – Name Server records

Later versions of this module will also allow for SRV, LOC, and CAA records. I am working on another terraform resource to handle the map type required.

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 via 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