Article · part of a guide
Terraform & OpenTofu .tfvars Cheatsheet
Quick cheat sheet for Terraform/OpenTofu .tfvars: syntax, file hierarchy, examples and pro tips. Download it now.

Key takeaways
- .tfvars files supply input variable values to Terraform and OpenTofu, separating configuration from core IaC code and applying only to variables declared in the root module.
- Terraform auto-loads terraform.tfvars, terraform.tfvars.json, and *.auto.tfvars files, while -var-file lets you load custom files explicitly.
- Variable precedence runs from lowest to highest: environment variables, then terraform.tfvars, then auto.tfvars files, then command-line flags, with later sources overriding earlier ones.
- OpenTofu is largely a drop-in replacement and reads the same TF_VAR_name environment variables as Terraform with no OpenTofu-specific prefix.
- Never commit plain-text secrets to version-controlled .tfvars files; sensitive = true redacts CLI output but not the state file, so secure your state.
1. What Are .tfvars Files For?
- Purpose:
tfvarsfiles supply input variable values to Terraform/OpenTofu, so you can customize each environment (dev, prod) without touching your core IaC code. - Benefits: Reusability, maintainability, separation of configuration from logic.
- Compatibility: Applies to both Terraform and OpenTofu.
2. How Do You Declare and Assign Variables?
Variable Declaration (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."
}
}- Key Arguments:
type,description,default,sensitive,validation.
Value Assignment (.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" }3. How Are tfvars and auto.tfvars Files Loaded?
- Automatic Loading (from root module directory):
terraform.tfvarsterraform.tfvars.json*.auto.tfvars(lexical order)*.auto.tfvars.json(lexical order)
- Explicit Loading (Command Line):
terraform apply -var-file="custom.tfvars"tofu plan -var-file="env/prod.tfvars"- Multiple
-var-fileflags can be used; loaded in order.
- Scope: Values from
tfvarsapply only to variables declared in the root module.
4. Which Variable Source Wins When Values Conflict?
- Environment Variables:
TF_VAR_name(OpenTofu honors the same prefix)
terraform.tfvarsfileterraform.tfvars.jsonfile (if both this andterraform.tfvarsexist, JSON usually overrides for the same variable)*.auto.tfvarsor*.auto.tfvars.jsonfiles (loaded alphabetically; later files override earlier ones)- Command-line flags (
-var="foo=bar"and-var-file="custom.tfvars"): Processed in order given; later flags override earlier ones. Highest precedence.
5. What Do Real tfvars Examples Look Like?
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"6. Does OpenTofu Handle tfvars Differently Than Terraform?
- Compatibility: Largely a drop-in replacement for Terraform regarding
tfvars. Still deciding between the two engines? See OpenTofu vs Terraform. - Environment Variables: OpenTofu reads the same
TF_VAR_nameenvironment variables as Terraform; there is no OpenTofu-specific prefix. - Documentation: Always refer to official OpenTofu docs for the latest specifics.
7. What Are the Best Practices for Using tfvars?
Multiple Environments
- Use distinct files (e.g.,
dev.tfvars,prod.tfvars). - Load explicitly with
-var-file. - Organize in a dedicated directory (e.g.,
tfvars/,environments/).
Security: Handling Sensitive Data
- GOLDEN RULE: NEVER commit plain-text secrets to version-controlled
tfvarsfiles. - Alternatives:
- Environment Variables (injected by CI/CD).
- Secrets Management Tools (Vault, AWS/Azure/GCP Secret Manager).
- IaC Platforms (Terraform Cloud, Spacelift). For a broader look at the options, see alternatives to Terraform Cloud and how each handles secure variables.
- Encryption (e.g., Mozilla SOPS).
**sensitive = true**: Invariables.tf, redacts from CLI output, NOT from state file. Secure your state file!
Version Control (.gitignore)
- Commit example files (e.g.,
terraform.tfvars.example). - Add actual
tfvarswith secrets/environment-specifics to.gitignore.
Clarity & Maintainability
- Use clear naming conventions for files and variables.
- Document variables thoroughly in
variables.tf(description). - Maintain consistency.
8. How Can You Automate and Scale tfvars Usage?
- Programmatic Generation:
terraform-docs tfvars hcl .(generates template)- Custom Scripts (Shell, Python) to fetch data and build
tfvars.
- CI/CD Integration:
- Store/generate
tfvarssecurely in CI/CD. - Use
-var-fileor environment variables in pipelines.
- Store/generate
- Workspaces (CLI):
- Use workspace-named
tfvars(e.g.,dev.tfvars). - Load with
terraform plan -var-file="${TERRAFORM_WORKSPACE}.tfvars".
- Use workspace-named
9. How Do You Troubleshoot Common tfvars Pitfalls?
- "Undeclared Variable": Variable in
tfvarsnot declared in.tffiles. Check typos. - File Loading/Naming Issues: Incorrect filename (e.g.,
terraform.tfvar) or location (must be in root module for auto-load). - Precedence Misunderstanding: Unexpected values due to overrides. Review precedence order.
- Syntax Errors: Invalid HCL/JSON. Validate syntax.
- Sensitive Data Exposure: Secrets in Git/state. Rotate secrets, implement proper management.
- Type Mismatches: Value in
tfvarsdoesn't matchtypeinvariabledeclaration.
Remember: Secure your state files, especially when using sensitive variables!
About the author

CEO at Scalr
Sebastian Stadil is the CEO of Scalr with 15+ years of DevOps experience. He started with AWS in 2004 and advised early Microsoft Azure and Google Cloud.
Part of this guide
6 sheets