Terraform多模块共用单个tfvars文件时的属性引用错误求助
Terraform多模块共用单个tfvars文件时的属性引用错误求助
嘿,我看你在Terraform多模块共用单个tfvars文件的时候遇到了属性引用的错误,咱们来一步步拆解问题,找到解决办法~
问题根源在哪?
你定义的var.market是一个包含tenant和webhook两个子对象的单一对象,当你把它传给for_each时,Terraform会把这个对象拆解成键值对集合来遍历——也就是说,each.key会依次是"tenant"和"webhook",而each.value对应的就是各自的子对象(比如遍历到tenant时,each.value直接就是{name = "some name", description = "some description", ...}这个对象)。这时候你再写each.value.tenant,相当于在一个已经是tenant内容的对象里找tenant属性,自然会报错说找不到啦。
不同场景的解决方案
场景1:只需要部署一个Tenant模块实例
如果你只是想用market里的tenant配置部署单个实例,完全不需要用for_each,直接引用var.market.tenant的属性就行:
module "tenant" { source = "./modules/Tenant" name = var.market.tenant.name description = try(var.market.tenant.description, null) country_code = var.market.tenant.country_code code = var.market.tenant.code }
场景2:需要同时部署Tenant和Webhook两个模块
如果你的目标是用同一个tfvars里的配置,分别部署tenant和webhook模块,那分开引用各自的配置块就好:
# 部署Tenant模块 module "tenant" { source = "./modules/Tenant" name = var.market.tenant.name description = try(var.market.tenant.description, null) country_code = var.market.tenant.country_code code = var.market.tenant.code } # 部署Webhook模块 module "webhook" { source = "./modules/Webhook" # 假设你有对应的Webhook模块 name = var.market.webhook.name description = var.market.webhook.description url = var.market.webhook.url tenant_code = var.market.webhook.tenant_code }
场景3:未来需要支持多个Tenant/Webhook实例
如果你的需求是以后要扩展成多个tenant或者多个webhook,那建议调整tfvars的结构,把同类资源的配置放到单独的map里,这样用for_each遍历起来更合理:
调整后的variables.tfvars
tenants = { tenant_prod = { name = "prod tenant" description = "production environment tenant" country_code = "US" code = "PROD-US" } tenant_staging = { name = "staging tenant" description = "staging environment tenant" country_code = "US" code = "STAGING-US" } } webhooks = { payment_webhook = { name = "payment notification" description = "receives payment status updates" url = "https://api.example.com/webhooks/payment" tenant_code = "PROD-US" } }
对应的main.tf配置
# 遍历所有tenant配置,部署多个Tenant实例 module "tenant" { source = "./modules/Tenant" for_each = var.tenants name = each.value.name description = try(each.value.description, null) country_code = each.value.country_code code = each.value.code } # 遍历所有webhook配置,部署多个Webhook实例 module "webhook" { source = "./modules/Webhook" for_each = var.webhooks name = each.value.name description = each.value.description url = each.value.url tenant_code = each.value.tenant_code }
补充:定义变量类型(很重要!)
为了让Terraform正确识别变量结构,避免潜在的类型错误,最好在variables.tf里明确变量类型:
# 场景1/2用到的market变量 variable "market" { type = object({ tenant = object({ name = string description = string country_code = string code = string }) webhook = object({ name = string description = string url = string tenant_code = string }) }) } # 场景3用到的tenants和webhooks变量 variable "tenants" { type = map(object({ name = string description = string country_code = string code = string })) } variable "webhooks" { type = map(object({ name = string description = string url = string tenant_code = string })) }
备注:内容来源于stack exchange,提问作者St.GunneR
相关产品推荐
相关产品推荐

