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

Terraform跨模块引用输出报错:无法访问列表对象属性

解决Terraform模块间引用输出值的列表属性错误

问题根源

你遇到的错误是因为module.azure-resource-group是列表类型而非单个对象。这是由于你在根目录1-resource-groups.tf中调用azure-resource-group模块时使用了count参数(类似count = var.cloud == "azure" ? 1 : 0),导致Terraform将模块实例化为长度为0或1的列表,而非单个对象。直接访问列表的属性会触发"Unsupported attribute"错误。

解决方案

方案1:通过索引访问列表元素(适用于单实例场景)

由于你的azure-storage-account模块同样使用count = var.cloud == "azure" ? 1 : 0,说明仅需在Azure环境下创建单个资源组和存储账户。此时可通过列表索引[0]获取资源组模块的实例,再访问其输出属性:

修改根目录2-storage.tf中的resource_group_name参数:

module "azure-storage-account" {
  count                       = var.cloud == "azure" ? 1 : 0
  source                      = "../../modules/azure/storage-account"
  resource_group_name         = module.azure-resource-group[0].resource-group-name
  storage_account_name        = "${var.storage_account_name}${var.environment}"
  location                    = var.location
  tags                        = var.tags
}

注:depends_on可省略,Terraform会自动识别模块间的依赖关系(通过resource_group_name的引用)。

方案2:移除模块的count参数(如果资源组始终需要创建)

如果资源组模块不需要条件创建(或条件逻辑已在模块内部处理),可移除根目录1-resource-groups.tf中azure-resource-group模块的count参数,使其成为单个对象。此时你原本的resource_group_name = module.azure-resource-group.resource-group-name写法即可正常工作。

额外说明

当模块使用count或for_each时,Terraform会将模块实例化为集合类型:

  • 使用count时,模块是列表,需通过索引(如[0])访问元素
  • 使用for_each时,模块是映射,需通过键(如["azure"])访问元素

只有当模块未使用count/for_each时,才能直接通过module.<name>.<output>的方式访问输出属性。

内容的提问来源于stack exchange,提问作者Shahar Hamuzim Rajuan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 02:05:13