How to use condition inside a for loop?

How do i use a condition inside a for_each such that , the below resource is created/triggered only when validation_method == “DNS” else ignores the creation of a resource. However in earlier terraform (11 versions) we can use count = var.validation_method == “DNS” ? length(var.domain_names) : 0
My var.domain_names is map(list(string)) , eg domain_names = {
foo.com” = ["*.foo.com"]
}

Please suggest me some solutions. Using terraform 0.12.20 version

resource "aws_route53_record" "validation" {
  for_each   = var.validation_method == "DNS" ? var.domain_names :
  name       = aws_acm_certificate.certificate[each.key].domain_validation_options.0.resource_record_name
  type       = aws_acm_certificate.certificate[each.key].domain_validation_options.0.resource_record_type
  zone_id    = data.aws_route53_zone.selected[each.key].zone_id
  ttl        = "300"
  records    = [aws_acm_certificate.certificate.domain_validation_options.0.resource_record_value]
  depends_on = [aws_acm_certificate.certificate.domain_name]
}

The main rule for for_each is that the map or set you assign must have the same number of elements as the number of instances you want to declare. The logical extreme of that rule is that if you use a collection with zero elements then you will get zero instances.

In a conditional expression where one of the expressions is a map type, as is the case for your var.domain_names, we can use empty {} to construct an empty map of the same type due to Terraform’s automatic type conversion rules:

  for_each = var.validation_method == "DNS" ? var.domain_names : {}

Terraform can see that var.domain_names is declared as map(list(string)) and therefore it knows that {} must be interpreted as an empty map of lists of strings (a map with zero elements), which is then an acceptable value for for_each to produce zero instances.

2 Likes