terraform config_error ai_generated true

Error: Reference to undeclared input variable: "var.environment" is not declared in the root module

ID: terraform/terraform-validate-undeclared-variable

Also available as: JSON · Markdown · 中文
90%Fix Rate
85%Confidence
1Evidence
2024-03-01First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
Terraform 1.0.0 active
Terraform 1.5.0 active
Terraform 1.6.0 active

Root Cause

A configuration file references a variable (var.*) that has not been declared with a variable block in any of the module's .tf files.

generic

中文

配置文件引用了变量(var.*),但该模块的任何 .tf 文件中都没有使用 variable 块声明该变量。

Official Documentation

https://developer.hashicorp.com/terraform/language/values/variables

Workarounds

  1. 95% success Declare the missing variable in a .tf file (e.g., variables.tf) with an appropriate type and optional default.
    Declare the missing variable in a .tf file (e.g., variables.tf) with an appropriate type and optional default.
  2. 85% success If the variable is meant to come from a module, ensure the module's outputs are correctly referenced. Use module.<module_name>.<output_name> instead of var.<name>.
    If the variable is meant to come from a module, ensure the module's outputs are correctly referenced. Use module.<module_name>.<output_name> instead of var.<name>.
  3. 80% success If the variable is not needed, replace the reference with a literal value or a local value.
    If the variable is not needed, replace the reference with a literal value or a local value.

中文步骤

  1. 在 .tf 文件(如 variables.tf)中声明缺失的变量,包含适当的类型和可选的默认值。
  2. 如果变量来自模块,确保正确引用模块的输出。使用 module.<module_name>.<output_name> 而不是 var.<name>。
  3. 如果不需要该变量,将引用替换为字面量或 local 值。

Dead Ends

Common approaches that don't work:

  1. 95% fail

    The .tfvars file only provides values; the variable must first be declared with a variable block in a .tf file.

  2. 80% fail

    Changing the prefix doesn't create the variable. 'local' requires a locals block, which is a different construct.

  3. 90% fail

    The issue is a missing variable declaration in the root module, not a missing module. Init doesn't add variable declarations.