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

Terraform Stacks组件引用模块输出报错:unsupported attribute

问题:Terraform Stacks引用组件输出报错"unsupported attribute"

我使用Terraform Stacks构建测试环境,将资源组、VNet、子网拆分为独立模块,先创建资源组再部署VNet等资源。但在VNet组件中引用资源组模块输出的resource_group_name时,收到错误提示:

unsupported attribute - this object does not have an attribute named "resource_group_name"

执行计划显示资源组名称能正确创建,且参考Hashicorp代码示例的语法似乎没问题,想知道遗漏了什么或操作有误。

相关代码

# input vars:
location = {
    dev = ["eastus2",]
    stage = ["eastus2",]
    prod = ["centralus","westus"]
}
environment = "dev"
app_name = "app1"

# components.tfstack.hcl:
component "rg" {
  for_each = var.location

  source = "./modules/rg"
  inputs = {
    name      = "${each.value}-${var.environment}-${var.app_name}-rg"
    location  = each.value
    tags      = var.tags
  }

  providers = {
    azurerm = provider.azurerm.this
  }
}

component "vnet" {
  for_each = var.location

  source = "./modules/vnet"
  inputs = {
    name                = "${each.value}-${var.environment}-${var.app_name}-vnet"
    location            = each.value
    resource_group_name = component.rg.resource_group_name
    address_space       = var.vnet_address_space
    tags                = var.tags
  }

  providers = {
    azurerm = provider.azurerm.this
  }
}

# resource group module:
resource "azurerm_resource_group" "rg" {
    name = var.name
    location = var.location

    tags = var.tags
}

output "resource_group_name" {
  value = azurerm_resource_group.rg.name
}

解决方案

问题核心是**component.rg是一个集合(因使用for_each),而非单个组件对象**,直接访问component.rg.resource_group_name会报错,因为集合本身没有该属性,需通过索引获取对应实例。

修改VNet组件中resource_group_name的引用,利用each.key匹配同位置的资源组实例:

component "vnet" {
  for_each = var.location

  source = "./modules/vnet"
  inputs = {
    name                = "${each.value}-${var.environment}-${var.app_name}-vnet"
    location            = each.value
    # 通过each.key索引对应位置的rg组件实例
    resource_group_name = component.rg[each.key].resource_group_name
    address_space       = var.vnet_address_space
    tags                = var.tags
  }

  providers = {
    azurerm = provider.azurerm.this
  }
}

当组件使用for_each时,component.<name>会转为映射结构,键为for_each的key,值为对应组件实例。由于rg和vnet的for_each都基于var.location,用each.key可精准匹配到当前循环对应的资源组组件,从而正确访问其输出属性resource_group_name。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 07:20:10