为何Terraform会抛出未声明输入变量引用错误?
项目文件夹结构
├── infrastructure │ ├── environments │ │ ├── production │ │ ├── backend.tvars │ │ ├── variable.tvars │ │ │ │ │ ├── modules │ ├── datadog-dashboard │ │ ├── main.tf │ │ ├── variables.tf │ │ │ └── datadog-monitors │ ├── backend.tf ├── main.tf ├── provider.tf ├── terraform.auto.tvars ├── variable.tfvars
错误信息
Error: Reference to undeclared input variable
│
│ on main.tf line 10, in module "rna_webapp_service_account":
│ 10: service = var.service
│
│ An input variable with the name "service" has not been declared.
This variable can be declared with a variable "service" {}
block.
根目录main.tf模块代码
module "rna_webapp_service_account" { source = "git::git..." service_account_name_override = "website ${var.environment_short}" display_name = "website ${var.environment_short}" description = "Service account for website ${var.environment_short}" service = var.service environment = var.environment_short location = var.location }
已声明的变量(根目录variables.tf)
variable "service" { description = "Name of the service the infrastructure is for" }
问题
明明已经在根目录的variables.tf中声明了service变量,为何运行流水线时仍提示该变量未声明?
可能的原因及解决办法
文件名混淆
从你的目录结构看,根目录只有variable.tfvars(变量值文件),没有variables.tf(变量声明文件)。Terraform的规则是:.tf后缀文件用于声明变量/资源,.tfvars后缀仅用于传递变量值。如果实际没有创建variables.tf,而是误把变量声明写在了.tfvars文件里,Terraform会无法识别变量声明。执行路径错误
检查流水线是否在根目录下执行terraform命令。如果流水线是进入infrastructure子目录运行,它不会读取根目录的variables.tf,自然找不到变量声明。变量声明文件未被加载
确认variables.tf确实存在于根目录,且文件名后缀是.tf。如果文件名是variable.tf(单数),虽然Terraform也会加载,但要确保文件内的变量声明语法正确,没有遗漏闭合符号或拼写错误。语法错误
检查variables.tf里的service变量声明是否有语法问题,比如少写了闭合的},或者variable关键字拼写错误。
内容的提问来源于stack exchange,提问作者GustaMan9000

