Cloudflare + Terraform DNS Records (Updated: 20191110)

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.

This module can maintain Cloudflare DNS records and is usable with the following DNS types:

    1. 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
SRV – Service records
CAA – Certification Authority Authorization records

Later versions of this module will also allow for LOC 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 example.com.tfvars 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.

EDIT 20190306: Converted reusable module to Terraform 0.12
EDIT 20191110: Cloudflare updated their provider and things broke along the way so this has been updated to support the new requirements. You will need to make a data call to get the resulting zone_id that is now required. I have updated the example code below that uses the module and the repository below has an updated README.

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

I created a data.tf file to do this for me within my terraform directory: