Home > Back-end >  Terraform for_each iteration over object
Terraform for_each iteration over object

Time:05-04

I'm relatively new to Terraform and I'm looking to simplify some private r53 zones I need to create using for_each.

I have the following local which I want to use to create private zones and associated A records in those zones:

locals {
  private_zones = [
    {
      name = "foo.com"
      txt = [
      "This is the txt record for foo.com"]
      ttl = 300
      records = {
        "host1" = "192.168.0.1",
        "host2" = "192.168.0.2"
      }
    },
    {
      name = "bar.com"
      txt = [
      "This is the txt record for bar.com"]
      ttl = 300
      records = {
        "host1" = "192.168.0.3",
        "host2" = "192.168.0.4"
      }
    }
  ]
}

I've found some code which will allow me to iterate over the local to create the zones

resource "aws_route53_zone" "zone" {
  for_each = { for name in local.private_zones : name.name => name }
  name     = each.value.name

  vpc {
    vpc_id = <vpc_id>
  }
}

but I've no idea how I can iterate and create A records in the respective zone using the records list in each local.

CodePudding user response:

You would use aws_route53_record and flattened private_zones:


locals {
    private_zones_flat = merge([
        for zone in local.private_zones: {
            for host, ip in zone.records:
                "${zone.name}-${host}" => {
                    zone_name = zone.name
                    host = host
                    ip = ip
                }
        }
    ]...)
}

resource "aws_route53_record" "host" {
  for_each = local.private_zones_flat
  zone_id = aws_route53_zone.zone[each.value.zone_name].zone_id
  name    = each.value.host
  type    = "A"
  ttl     = "300"
  records = [each.value.ip]
}
  • Related