What’s a good way to handle optional dynamic blocks, depending on existence of map keys?
Example: Producing aws_route53_record resources, where they can have either a “records” list, or an “alias” block, but not both. I’m using Terraform 0.12.6.
I’m supplying the entire Route53 zone YAML as a variable, through yamldecode():
zone_id: Z987654321
records:
- name: route53test-plain.example.com
type: A
ttl: 60
records:
- 127.0.0.1
- 127.0.0.2
- name: route53test-alias.example.com
type: A
alias:
name: "foo.bar.baz"
zone_id: "Z12345678"
evaluate_target_health: false
Terraform config:
#variable "zone_data" {
# type = object({
# zone_id = string
# records = list(object({
# name = string
# type = string
# ttl = any # optional
# records = list(string) # optional
# alias = object({ # optional
# name = string
# zone_id = string
# evaluate_target_health = bool
# })
# }))
# })
#}
variable "zone_data" {}
resource "aws_route53_record" "record" {
for_each = { for v in var.zone_data.records : "${v.name}-${v.type}" => v }
zone_id = var.zone_data.zone_id
name = each.value.name
type = each.value.type
ttl = lookup(each.value, "ttl", null) # ttl is optional
records = lookup(each.value, "records", null) # records is optional
dynamic "alias" {
for_each = lookup(each.value, "alias", {})
content {
name = each.value.name
zone_id = each.value.zone_id
evaluate_target_health = each.value.evaluate_target_health
}
}
}
What’s a good way to handle the optional “alias” (and “ttl”, “records”) block here?
I’m currently getting errors like these:
42: zone_id = each.value.zone_id
|----------------
| each.value is object with 4 attributes
This object does not have an attribute named "zone_id".
Is lookup() the right thing to use when keys may be missing?