首页 > 解决方案 > Terraform:在另一个资源中引用在 for_each 中创建的资源

问题描述

当我有一个托管区域时,我很容易创建该区域,然后通过按名称引用托管区域来在委派帐户中为该区域创建 NS 记录。

现在我需要创建多个托管区域并将名称服务器记录传递回父帐户,我不确定它是否可能(或如何)引用多个资源。阅读这篇文章可能没有多大意义,所以下面的代码就我所知。

我现在有一个for_each循环,它将遍历字符串列表并为每个字符串创建一个托管区域,然后我想在另一个帐户中创建相应的 NS 记录,请注意我正在使用单独的提供程序provider = aws.management_account连接到管理帐户和这适用于单个托管区域。

我不知道如何引用托管区域,是否有一些语法或我的方法错误?

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]
  ]
}

标签: amazon-web-servicesforeachterraformamazon-route53

解决方案


由于你local.aws_zones的设置为 ["dev", "test", "qa"],你aws_route53_zone.public_hosted_zone将是一个带有键 "dev"、"test"、"qa" 的映射。

因此,要在您的 中使用它aws_route53_record,您可以尝试:

resource "aws_route53_record" "ns_records" {
  for_each        = local.aws_zones

  # other attributes

  records = aws_route53_zone.public_hosted_zone[each.key].name_servers
}

推荐阅读