
tfvars files supply input variable values to Terraform/OpenTofu, enabling environment customization (dev, prod) without altering core IaC code.variables.tf)variable "variable_name" {
type = string # Or number, bool, list, map, object, etc.
description = "Purpose of the variable."
default = "optional_default_value"
sensitive = false # Set to true to redact from CLI output (not state!)
validation {
condition = length(var.variable_name) > 0
error_message = "Value must not be empty."
}
}type, description, default, sensitive, validation..tfvars files)Example (terraform.tfvars):
instance_type = "t2.medium"
aws_region = "us-east-1"Syntax (JSON - *.tfvars.json):
{
"variable_name": "value",
"list_variable": ["item1", "item2"],
"map_variable": {
"key1": "val1",
"key2": "val2"
}
}Syntax (HCL - *.tfvars):
variable_name = "value"
list_variable = ["item1", "item2"]
map_variable = { key1 = "val1", key2 = "val2" }terraform.tfvarsterraform.tfvars.json*.auto.tfvars (lexical order)*.auto.tfvars.json (lexical order)terraform apply -var-file="custom.tfvars"tofu plan -var-file="env/prod.tfvars"-var-file flags can be used; loaded in order.tfvars apply only to variables declared in the root module.TF_VAR_nameOPENTOFU_VAR_name (takes precedence over TF_VAR_ if both set for OpenTofu)terraform.tfvars fileterraform.tfvars.json file (if both this and terraform.tfvars exist, JSON usually overrides for the same variable)*.auto.tfvars or *.auto.tfvars.json files (loaded alphabetically; later files override earlier ones)-var="foo=bar" and -var-file="custom.tfvars"): Processed in order given; later flags override earlier ones. Highest precedence.Complex Types (services.tfvars for list(object(...))):
// Assuming variable "app_services" is list(object({ name=string, instance_type=string, port=number }))
app_services = [
{ name = "frontend", instance_type = "t3.medium", port = 80 },
{ name = "backend", instance_type = "t3.large", port = 8080 }
]Simple Values (dev.tfvars):
instance_count = 2
enable_monitoring = false
environment_name = "development"tfvars.TF_VAR_ but OPENTOFU_VAR_name takes precedence if both are set. Recommend using OPENTOFU_VAR_ for new OpenTofu projects.dev.tfvars, prod.tfvars).-var-file.tfvars/, environments/).tfvars files.**sensitive = true**: In variables.tf, redacts from CLI output, NOT from state file. Secure your state file!.gitignore)terraform.tfvars.example).tfvars with secrets/environment-specifics to .gitignore.variables.tf (description).terraform-docs tfvars hcl . (generates template)tfvars.tfvars securely in CI/CD.-var-file or environment variables in pipelines.tfvars (e.g., dev.tfvars).terraform plan -var-file="${TERRAFORM_WORKSPACE}.tfvars".tfvars not declared in .tf files. Check typos.terraform.tfvar) or location (must be in root module for auto-load).tfvars doesn't match type in variable declaration.Remember: Secure your state files, especially when using sensitive variables!
