Automating Cloudflare DNS management with Terraform

Abeer Alotaibi
2 min readApr 23, 2021

--

This post is about managing Cloudflare zones and records in a declarative and version-controlled way, as a part of our journey to the infrastructure-as-code practices.

Terraform has published a verified Cloudflare provides in Terraform registry that’s used to interact with most of the resources supported by Cloudflare. I used this provider to automate the process of creating DNS zones and controlling DNS records (create, update and delete).

Requirements:

Terraform installed on your machine.

  • Terraform module called: dns_management includes two Cloudflare resources (DNS zone and records).
resource "cloudflare_zone" "dns_zones" {
for_each = var.dns_zones

zone = each.key
plan = each.value.plan
}


resource "cloudflare_record" "dns_records" {
for_each = var.dns_records

zone_id = each.value.zone_id
name = each.key
value = each.value.value
type = each.value.type
ttl = each.value.ttl
proxied = each.value.proxied

}

Above module requires some variables to be defined in variables.tf file as below.

variable "dns_records" {
type = map(object({
zone_id = string
value = string
type = string
ttl = number
proxied = string

}))
description = "map of DNS records information"
}

variable "dns_zones" {
type = map(object({
plan = string
}))
description = "DNS zone information"
}

Although it’s simple, the benefit of defining Cloudflare resources as a module is to make is reusable and make the main file where we will add dns records more readable and avoid repating ourselves :D.

example use of the above module.

module "dns_zones" {
source = "./dns_management"

dns_zones = {
"example.sa" = {
plan = "free"
}
}
dns_records = {
"terraform.example.sa" = {
zone_id = local.zones_info.example_sa_id
value = "193.192.70.30"
type = "A"
ttl = 1
proxied = false
}

by running terraform plan in the above example, it will show that there are 2 resources that will be added to your Cloudflare account .. Changes can be applied by terraform apply .

Module repo on GitHub

For more details please refer to Cloudflare provider documentations in Terraform registry here.

Cheers,
Abeer Alotaibi

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

No responses yet

Write a response