Terraform跨模块引用输出报错:trgroup无target_group_arn属性
使用Terraform v1.3.8,项目采用模块化架构,在listener模块中引用trgroup模块的target_group_arn输出时,出现以下报错:
Error: Unsupported attribute
│
│ on main.tf line 24, in module "listener":
│ 24: target_group_arn = module.trgroup.target_group_arn
│ ├────────────────
│ │ module.trgroup is object with 7 attributes
│
│ This object does not have an attribute named "target_group_arn".
原因分析
trgroup模块使用了for_each = var.services,这会让module.trgroup变成一个映射对象(键为var.services的键,值为对应模块实例),而非单个模块实例。直接访问module.trgroup.target_group_arn相当于在映射对象上找全局的target_group_arn属性,自然不存在。
解决方案
因为listener模块同样使用for_each = var.services,可以通过each.key匹配对应的trgroup实例,修改listener模块的target_group_arn参数:
# Load balancer listener module "listener" { source = "../modules/listener" for_each = var.services listener_count = each.value.listener_count application = var.application listener_port = each.value.listener_port ssl_policy = each.value.ssl_policy certificate_arn = module.cloudfront.certificate_arn load_balancer_arn = module.alb.internal_alb listener_protocol = each.value.listener_protocol listener_rule_count = each.value.listener_rule_count type = each.value.target_type # 修改这里,通过each.key匹配对应的trgroup实例 target_group_arn = module.trgroup[each.key].target_group_arn srv = each.key }
说明
当模块启用for_each后,必须通过键(这里就是each.key,对应var.services中的每个服务名)来访问具体实例的输出属性,module.trgroup[each.key]会定位到当前listener实例对应的trgroup实例,进而获取其target_group_arn输出。
内容的提问来源于stack exchange,提问作者Sosh

