Terraform读取YAML值配置AWS Route53区域与解析记录实现咨询
实现方案
1. 加载YAML配置
首先将你的YAML配置保存为domains.yaml文件,在Terraform中通过本地值加载解析配置,同时打平嵌套的子域名记录,方便后续批量创建资源:
locals { # 读取并解析YAML配置文件 domain_config = yamldecode(file("${path.module}/domains.yaml")) source_domains = local.domain_config.source_domains # 打平所有子域名记录,每个子域名生成一个独立配置项 flattened_records = flatten([ for domain in local.source_domains : [ for record in domain.records : { apex_name = domain.apax_name # 注意YAML中写的是apax_name,若为apex_name的笔误请同步修改 record_name = record } ] ]) }
如果你是直接把
source_domains作为Terraform输入变量使用,不需要加载YAML的话可以去掉上述配置,直接替换后续代码中的local.source_domains为var.source_domains即可,变量定义参考:variable "source_domains" { type = list(object({ apax_name = string records = list(string) })) }
2. 修正Route53 Zone资源配置
使用根域名作为for_each的稳定唯一键,避免后续配置变更时误删重建资源:
resource "aws_route53_zone" "this" { for_each = { for domain in local.source_domains : domain.apax_name => domain } name = each.key # 可按需补充私有域、标签等其他配置项 }
3. 修正Route53 Record资源配置
遍历打平后的子域名列表,批量创建对应A记录:
resource "aws_route53_record" "this" { for_each = { for rec in local.flattened_records : "${rec.apex_name}_${rec.record_name}" => rec } zone_id = aws_route53_zone.this[each.value.apex_name].zone_id name = each.value.record_name type = "A" ttl = 300 # 可按需调整缓存时间 records = ["192.168.0.1"] # 若记录值需要从YAML取值可自行扩展配置结构 }
注意事项
- 请确认YAML中的
apax_name是否为apex_name的拼写错误,如果是请同步修改YAML文件和代码中的对应键名,避免取值失败 - 配置执行后会自动为每个根域名创建公有托管Zone,同时为所有配置的子域名添加对应A记录,完全匹配你的需求
内容的提问来源于stack exchange,提问作者awiechert
相关产品推荐
相关产品推荐

