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

使用for_each调用Terraform模块时输出id属性报错求助

问题分析与解决方案

报错的核心原因是:当使用for_each调用模块时,module.subscription_template_sb不再是单个模块实例,而是一个映射(map)结构——键对应var.topic_subscription中的sub1、sub2,值是对应的模块实例。如果直接尝试引用module.subscription_template_sb.sb_value,Terraform会判定映射对象本身没有sb_value属性,进而抛出类似This object does not have an attribute named "id"的错误(本质是访问方式错误导致无法定位到具体资源的id)。

解决方法

根据你的需求选择对应方式:

1. 输出所有订阅的ID

在根模块的输出配置中,用for表达式遍历模块集合,生成包含所有订阅ID的映射:

output "all_subscription_ids" {
  value = {
    for sub_key, module_inst in module.subscription_template_sb : sub_key => module_inst.sb_value
  }
}

2. 单独引用某个订阅的ID

直接通过模块集合的键,访问对应实例的输出:

# 示例:引用sub1对应的订阅ID
output "sub1_subscription_id" {
  value = module.subscription_template_sb["sub1"].sb_value
}

3. 验证模块内部配置(确保基础正确性)

确认模块subscription_template_sb的variables.tf中已正确定义sb变量:

variable "sb" {
  type        = string
  description = "Name of the Pub/Sub topic"
}

上述调整后,Terraform会正确定位到单个模块实例中的资源id属性,问题即可解决。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 15:17:18