Search code examples
amazon-web-servicesforeachterraformamazon-route53

Terraform: Referencing resources created in for_each in another resource


When I had a single hosted zone it was easy for me to create the zone and then create the NS records for the zone in the delegating account by referencing the hosted zone by name.

Now I need to create multiple hosted zones and pass the nameserver records back to the parent account and I am not sure if its possible (or how if it is) to reference multiple resources. Reading this probably doesn't make a whole lot of sense, so the code below is as far as I have got.

I now have a for_each loop which will loop over a list of strings and create a hosted zone for each string, and I want to then create corresponding NS records in another account, notice that I am using a separate provider provider = aws.management_account to connect to the management account and this works fine for a single hosted zone.

I do not know how to reference the hosted zones, is there some syntax for this or is my approach wrong?

resource "aws_route53_zone" "public_hosted_zone" {
  for_each = local.aws_zones
  name     = "${each.value}.${var.domain}"
}

resource "aws_route53_record" "ns_records" {
  for_each        = local.aws_zones
  provider        = aws.management_account
  allow_overwrite = true
  name            = "${each.value}.${var.domain}"
  ttl             = 30
  type            = "NS"
  zone_id         = data.aws_ssm_parameter.public_hosted_zone_id.value

  records = [
    aws_route53_zone.public_hosted_zone.name_servers[0], # Here is my old code which works for a single hosted zone but I cannot work out how to reference multiples created above
    aws_route53_zone.public_hosted_zone.name_servers[1],
    aws_route53_zone.public_hosted_zone.name_servers[2],
    aws_route53_zone.public_hosted_zone.name_servers[3]
  ]
}

Solution

  • Since your local.aws_zones is set ["dev", "test", "qa"], your aws_route53_zone.public_hosted_zone will be a map with keys "dev", "test", "qa".

    Therefore, to use it in your aws_route53_record, you can try:

    resource "aws_route53_record" "ns_records" {
      for_each        = local.aws_zones
    
      # other attributes
    
      records = aws_route53_zone.public_hosted_zone[each.key].name_servers
    }