Terraform & OpenTofu .tfvars Cheatsheet
Quick cheat sheet for Terraform/OpenTofu .tfvars: syntax, file hierarchy, examples and pro tips—download it now.
1. Core Concept
- Purpose:
tfvarsfiles supply input variable values to Terraform/OpenTofu, enabling environment customization (dev, prod) without altering core IaC code. - Benefits: Reusability, maintainability, separation of configuration from logic.
- Compatibility: Applies to both Terraform and OpenTofu.
2. Variables & Values
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 Variables are 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. Variable Precedence (Lowest to Highest)
- Environment Variables:
TF_VAR_nameOPENTOFU_VAR_name(takes precedence overTF_VAR_if both set for OpenTofu)
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. Common Examples
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. OpenTofu Specifics
- Compatibility: Largely a drop-in replacement for Terraform regarding
tfvars. - Environment Variables: Honors
TF_VAR_butOPENTOFU_VAR_nametakes precedence if both are set. Recommend usingOPENTOFU_VAR_for new OpenTofu projects. - Documentation: Always refer to official OpenTofu docs for the latest specifics.
7. Best Practices
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).
- 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. Advanced Techniques
- 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. Troubleshooting Common 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!