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

Terraform调用模块变量已声明仍报未定义错误排查

问题原因
  • 核心错误是Terraform子模块调用的参数名不匹配:调用子模块时传入的参数名必须和子模块variables.tf中声明的变量名完全一致。你在Bastion子模块中声明的变量名是bastion_allocation_method、bastion_sku_type,但根模块调用时错误将参数简写为allocation_method、sku,直接触发两类报错:
    • 子模块标记为必填的bastion_allocation_method、bastion_sku_type参数未收到传入值,抛出Missing required argument错误
    • 传入的allocation_method、sku不属于子模块定义的合法输入参数,抛出Unsupported argument错误
  • 存在两个额外配置问题:
    • terraform.tfvars使用了JSON格式的键值写法(键加双引号、键值用冒号分隔),不符合Terraform HCL的语法要求
    • Bastion子模块的variables.tf未声明调用时传入的rg_name、location、prefix、postfix、subnet_id参数,修正参数名后会继续报不支持参数的错误
修正步骤
  1. 修改根目录下bastion.tf的模块调用块,将参数名调整为和子模块变量名完全一致:
module "bastion" {
  source                    = "../modules/bastion"
  rg_name                   = module.resource_group.name
  location                  = module.resource_group.location
  bastion_allocation_method = var.bastion_allocation_method
  bastion_sku_type          = var.bastion_sku_type
  prefix                    = var.prefix
  postfix                   = random_string.postfix.result
  subnet_id                 = azurerm_subnet.bastion_subnet.id
}
  1. 修改terraform.tfvars为标准HCL语法格式:
bastion_allocation_method = "Static"
bastion_sku_type          = "Standard"
  1. 补全Bastion子模块下variables.tf的变量声明,和调用时传入的参数一一对应:
variable "bastion_allocation_method" {
  type        = string
  description = "allocation method for bastion"
}

variable "bastion_sku_type" {
  type        = string
  description = "sku to be used for bastion"
}

variable "rg_name" {
  type        = string
  description = "资源组名称"
}

variable "location" {
  type        = string
  description = "资源部署区域"
}

variable "prefix" {
  type        = string
  description = "资源名称前缀"
}

variable "postfix" {
  type        = string
  description = "资源名称后缀"
}

variable "subnet_id" {
  type        = string
  description = "Bastion服务所在子网ID"
}

完成以上修改后,执行terraform init重载模块配置,再运行terraform plan即可正常生成执行计划。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 05:42:31