csaju
csaju

Reputation: 394

Reuse the terraform cloudflare module for root domain with subdomain configuration

Here I wanted to use the existed Cloudflare module to include root domain configuration. How can I make it reusable for the root domain with its respective DNS type in the single module record and make it in a single module?

main.tf

module "record" {

  for_each = toset(local.aliases)

  source          = "./modules/cloudflare"
  zone_id         = data.cloudflare_zone.domain.id
  name            = each.key
  value           = aws_cloudfront_distribution.s3_distribution.domain_name
  dns_type        = "CNAME" 
  proxied         = false
  allow_overwrite = true
  depends_on      = [aws_cloudfront_distribution.s3_distribution]
}

module "record_for_root_domain" {

  source          = "./modules/cloudflare"
  zone_id         = data.cloudflare_zone.domain.id
  name            = var.root_domain
  value           = aws_cloudfront_distribution.s3_distribution.domain_name
  dns_type        = "A"
  proxied         = false
  allow_overwrite = true
  depends_on      = [aws_cloudfront_distribution.s3_distribution]
}

locals.tf

locals {
  aliases                    = formatlist("%s.${var.domain}", var.services)
  main_domain                = "*.${var.domain}"
}

Upvotes: 0

Views: 535

Answers (1)

javierlga
javierlga

Reputation: 1652

Create a new Terraform variable as a list of objects:

variable "dns_records" {
  description = "A list of DNS records to create"
  variable = list(object({
    record_name = string
    record_type = string
  }))
}

Then you reuse it like this:

module "record_for_root_domain" {
  for_each        = { for record in var.dns_records : record.record_name => record }
  source          = "./modules/cloudflare"
  
  zone_id         = data.cloudflare_zone.domain.id
  name            = each.value.record_name
  value           = aws_cloudfront_distribution.s3_distribution.domain_name
  dns_type        = each.value.record_type
  proxied         = false
  allow_overwrite = true
  depends_on      = [aws_cloudfront_distribution.s3_distribution]
}

Upvotes: 1

Related Questions