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参数,修正参数名后会继续报不支持参数的错误
修正步骤
- 修改根目录下
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 }
- 修改
terraform.tfvars为标准HCL语法格式:
bastion_allocation_method = "Static" bastion_sku_type = "Standard"
- 补全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
相关产品推荐
相关产品推荐

