You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Terraform中如何根据条件向数组添加Route53记录对象

解决方案

你可以用Terraform的concat函数搭配条件表达式,实现仅当each.value.create_wild_card为true时才添加通配符Route53记录:

module "r53_records" {
  for_each = var.s3_static_websites[terraform.workspace]
  source   = "terraform-aws-modules/route53/aws//modules/records"
  version  = "~> 2.0"

  zone_name = each.value.zone

  records = concat(
    [
      {
        name    = each.value.sub_domain
        type    = "CNAME"
        records = [module.cdn[each.key].cloudfront_distribution_domain_name]
        ttl     = 300
      }
    ],
    each.value.create_wild_card ? [
      {
        name    = "*"
        type    = "CNAME"
        records = [module.cdn[each.key].cloudfront_distribution_domain_name]
        ttl     = 300
      }
    ] : []
  )
}

逻辑说明

  • concat负责合并两个数组:第一个数组是必须存在的子域名CNAME记录;第二个数组通过三元运算符判断——如果create_wild_card为真,就传入包含通配符记录的数组,否则传入空数组[],这样就不会往最终的records里加额外元素。
  • 这种写法既满足了条件添加的需求,又能保持代码结构清晰。

内容的提问来源于stack exchange,提问作者Ste

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 17:07:27