'Terraform: creation of resources with nested loop

I have created a bunch of VPC endpoints in one AWS account and need to share them with other VPCs across different accounts. Break down of my terraform code is provided below.

  • Created the Route53 private hosted zones (Resource#1 for easy reference) as below
resource "aws_route53_zone" "private" {
  for_each      = local.vpc_endpoints

  name = each.value.phz

  vpc {
    vpc_id = var.vpc_id
  }

  lifecycle {
    ignore_changes = [vpc]
  }

  tags = {
    Name = each.key
  }
}
  • Created vpc association authorizations (Resource#2). The VPC ID, to which the endpoints are to be shared is passed as a variable as shown below.
resource "aws_route53_vpc_association_authorization" "example" {
  for_each      = local.vpc_endpoints

  vpc_id  = var.vpc
  zone_id = aws_route53_zone.private[each.key].zone_id
}
  • Finally, I have created the VPC associations (Resource#3)
resource "aws_route53_zone_association" "target" {
  for_each = aws_route53_vpc_association_authorization.example
  provider = aws.target-account

  vpc_id  = aws_route53_vpc_association_authorization.example[each.key].vpc_id
  zone_id = aws_route53_vpc_association_authorization.example[each.key].zone_id
}

Everything works fine for the first VPC (vpc-A). But now I need to share the same hosted zones (Resource#1) with a different VPC (vpc-B) and more VPCs in the future. This means I need to repeat the creation of "aws_route53_vpc_association_authorization" (Resource#2) for all new VPCs as well, ideally looping through a list of VPC IDs. But I am unable to it as nested for_each loop is not supported. Tried other options like count + for_each etc., but nothing help.

Could you provide some guidance on how to achieve this?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source