terraform dynamic bloc with two iterations

84 views Asked by At

I have a dynamic bloc in terraform which content has two dynamic arguments as we can't use for_each twice in the same bloc is there a way to use dynamic bloc in this case

locals {  
   mx_server = [ "smtp.mydomain.com.", "mail.mydomain.com."]
   preference = [ 5, 10 ]
}

resource "dns_mx_record_set" "mx" {
  for_each = toset(var.dns_zones)
  zone = "${each.value}."
  ttl  = 300

  dynamic "mx" {
    for_each = toset(local.mx_server)
    content {
      exchange = mx.value
      preference = 10
    }    
  }
}

Here I would like to iterate also on preference argument. What is expected as result is the same thing if I don't use any iteration

resource "dns_mx_record_set" "mx" {
  for_each = toset(var.dns_zones)
  zone = "${each.value}."
  ttl  = 300

  "mx" {
      exchange = smtp.mydomain.com
      preference = 5
    }
 "mx" {
      exchange = mail.mydomain.com
      preference = 10
    }
  }
}

the question is how to loop on exchange and preference argument at the same time when I can't use for_each twice in the same block

1

There are 1 answers

0
Marcin On

You can use setproduct:


resource "dns_mx_record_set" "mx" {
  for_each = toset(var.dns_zones)
  zone = "${each.value}."
  ttl  = 300

  dynamic "mx" {
    for_each = setproduct(local.mx_server, local.preference)
    content {
      exchange = mx.value[0]
      preference = mx.value[1]
    }    
  }
}