Home > Net >  terraform multiple aws route53 alias records under locals
terraform multiple aws route53 alias records under locals

Time:03-29

I have a set of AliasRecords under terraform locals and wanted to map them under terraform's resource "aws_route53_record" . Below is the locals value:

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

What I am doing is :

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

and when pushing to AWS ( terraform apply), it fails with below error:

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

│ This value does not have any indices.

CodePudding user response:

Your AWSAliasRecordSets does not require flattening, as it is already flat. Thus you can go use regular count for it.

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

You also have to double check your use of Name and DNSName. Your current usage does not seem right to me, but this would be a new issue if this is really the case.

  • Related