本地人下的 terraform 多个 aws route53 别名记录

terraform multiple aws route53 alias records under locals

我在 terraform locals 下有一组 AliasRecords,想将它们映射到 terraform 的 resource "aws_route53_record" 下。以下是本地值:

locals {
    AWSAliasRecordSets = [
              {
                  Name =  "api-dev.example.com.",
                  Type =  "A",
                  AliasTarget =  {
                      HostedZoneId =  "EXAMPLE",
                      DNSName =  "kjhskdjhf.cloudfront.net.",
                      EvaluateTargetHealth =  false
                  }
              },
              {
                  Name =  "api.example.com.",
                  Type =  "A",
                  AliasTarget =  {
                      HostedZoneId =  "EXAMPLE",
                      DNSName =  "jsdhgfjkdshf.cloudfront.net.",
                      EvaluateTargetHealth =  false
                  }
              }
    ]
}

我正在做的是:

locals {
    FlatAWSAliasRecordSets = merge([
    for idx, AWSAliasRecordSet in local.AWSAliasRecordSets:
      {
        for AliasTarget in AWSAliasRecordSet.AliasTarget:
            "${idx}-${AliasTarget}" => {
              HostedZoneId          =  AliasTarget["HostedZoneId"]
              DNSName               =  AliasTarget["DNSName"]
              EvaluateTargetHealth  =  AliasTarget["EvaluateTargetHealth"]
          }
      }
    ]...)
}

resource "aws_route53_record" "alias_records" {
  for_each = local.FlatAWSAliasRecordSets
  zone_id  = each.value["HostedZoneId"]
  name     = each.value["AliasTarget"].Name
  type     = each.value["AliasTarget"].Type

  alias {
    zone_id                = each.value["HostedZoneId"]
    name                   = each.value["AliasTarget"].Name
    evaluate_target_health = each.value["EvaluateTargetHealth"]
  }
}

并且在推送到 AWS 时(terraform 应用),它失败并出现以下错误:

│   on main.tf line 508, in locals:
│  508:               EvaluateTargetHealth  =  AliasTarget["EvaluateTargetHealth"] 

│ This value does not have any indices.

您的 AWSAliasRecordSets 不需要展平,因为它已经展平了。因此,您可以使用常规的 count

resource "aws_route53_record" "alias_records" {
  count    = length(local.AWSAliasRecordSets)
  zone_id  = local.AWSAliasRecordSets[count.index]["AliasTarget"].HostedZoneId
  name     = local.AWSAliasRecordSets[count.index].Name
  type     = local.AWSAliasRecordSets[count.index].Type

  alias {
    zone_id                = local.AWSAliasRecordSets[count.index]["AliasTarget"].HostedZoneId
    name                   = local.AWSAliasRecordSets[count.index].DNSName
    evaluate_target_health = each.value["AliasTarget"].EvaluateTargetHealth
  }
}

您还必须仔细检查您对 NameDNSName 的使用。您当前的用法对我来说似乎不正确,但如果确实如此,这将是一个新问题。