Default DNS records in every zone managed via terraform (eg. MX records)

369 views Asked by At

I'm looking for a way to manage cloudflare zones and records with terraform and create some default records (eg. MX) in every zone that is managed via terraform, something like this:

resource "cloudflare_zone" "example_net" {
  type   = "full"
  zone   = "example.net"
}

resource "cloudflare_zone" "example_com" {
  type   = "full"
  zone   = "example.com"
}

resource "cloudflare_record" "mxrecord"{
  for_each=cloudflare_zone.*
  name     = "${each.value.zone}"
  priority = "1"
  proxied  = "false"
  ttl      = "1"
  type     = "MX"
  value    = "mail.foo.bar"
  zone_id  = each.value.id
}

Does anyone have a clue for me how to achieve this (and if this is even possible...)? Thanks a lot!

2

There are 2 answers

0
Styszma On

You could create a module responsible for the zone resource, e.g.:

# modules/cf_zone/main.tf
resource "cloudflare_zone" "cf_zone" {
  type   = "full"    
  zone = var.zone_name
}

resource "cloudflare_record" "mxrecord"{
  name     = "${cloudflare_zone.cf_zone.name}"
  priority = "1"
  proxied  = "false"
  ttl      = "1"
  type     = "MX"
  value    = "mail.foo.bar"
  zone_id  = "${cloudflare_zone.cf_zone.id}"
}

# main.tf

module "example_net" {
  source = "./modules/cf_zone"
  zone_name = "example_net"
}

module "example_com" {
  source = "./modules/cf_zone"
  zone_name = "example_com"
}

This would give you an advantage on creation of default resources and settings per zone (DNS entries, security settings, page rules, etc.). It is also a good way to keep all the default values in a single place for review. You can ready more about terraform modules here.

0
fallincode On

This is easy to do if you use a module, as was correctly noted in the other answer, but you don't have to create one, you can use this module.

Then your configuration will look like this:

terraform {
  required_providers {
    cloudflare = {
      source = "cloudflare/cloudflare"
    }
  }
}

variable "cloudflare_api_token" {
  type        = string
  sensitive   = true
  description = "The Cloudflare API token."
}

provider "cloudflare" {
  api_token = var.cloudflare_api_token
}

locals {
  domains = [
    "example.com",
    "example.net"
  ]
  mx = "mail.foo.bar"
}

module "domains" {
  source  = "registry.terraform.io/alex-feel/zone/cloudflare"
  version = "1.8.0"

  for_each = toset(local.domains)

  zone = each.value

  records = [
    {
      record_name = "mx_1"
      type        = "MX"
      value       = local.mx
      priority    = 1
    }
  ]
}

You can find an example of using this module that matches your question here.