Search code examples
amazon-web-servicesterraformterraform-provider-awsamazon-route53

generating a routing policy block based on condition in terraform


Some of my ingresses are geo aware and some are not I want to add the geolocation routing policy based on the condition.

I have tried creating it using dynamic block but missing something on the logic part.

This is what my main.tf and variables.tf files looks like

resource "aws_route53_record" "ingress_records" {
  for_each        = var.ingresses
  name            = each.key
  type            = var.record_type
  zone_id         = "abxklslkdlksdj..aasas"
  records         = [each.value["ingress"] == "external_nginx" ? var.external_nginx : var.internal_nginx]
  ttl             = each.value["ttl"]
  allow_overwrite = true
  set_identifier  = "ingresses"
  dynamic "geolocation_routing_policy" {
    for_each = [for i in var.ingresses : [1] if i.geolocation == true ]
    content {
      country = var.country
   }
  }
 }

Variables.tf

variable "ingresses" {
  type = map(object({
    ttl         = number
    ingress     = string
    geolocation = bool
  }))

  default = {
    "abc.com" = {
      ttl         = 300
      ingress     = "external_nginx"
      geolocation = true
    }

   "abx.com" = {
      ttl         = 60
      ingress     = "external_nginx"
      geolocation = false
    }
}

Upon running the code getting this error please help

│ Error: Too many geolocation_routing_policy blocks
│ 
│   on main.tf line 16, in resource "aws_route53_record" "ingress_records":
│   16:     content {
│ 
│ No more than 1 "geolocation_routing_policy" blocks are allowed

How can I avoid geolocation block part from repeating itself more than once?


Solution

  • You don't need to perform a for loop inside the condition, you just need to look up the setting for the specific domain name you are creating a record for:

    for_each = var.ingresses[each.key].geolocation ? [1] : []
    

    The above will look up the var.ingresses configuration for the specific domain name (the value in each.key), and set the for_each iterator to a list of size 1 if geolocation is true, or a list of size 0 if geolocation is false.