TrademarkTrademark
Features
Documentation
  1. Learning Center
  2. Terraform tfvars: A Practical Guide to .tfvars Files and Variables

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.

Terraform & OpenTofu .tfvars Cheatsheet

Key takeaways

  1. .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.
  2. Terraform auto-loads terraform.tfvars, terraform.tfvars.json, and *.auto.tfvars files, while -var-file lets you load custom files explicitly.
  3. 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.
  4. OpenTofu is largely a drop-in replacement and reads the same TF_VAR_name environment variables as Terraform with no OpenTofu-specific prefix.
  5. 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: tfvars files 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):
    1. terraform.tfvars
    2. terraform.tfvars.json
    3. *.auto.tfvars (lexical order)
    4. *.auto.tfvars.json (lexical order)
  • Explicit Loading (Command Line):
    • terraform apply -var-file="custom.tfvars"
    • tofu plan -var-file="env/prod.tfvars"
    • Multiple -var-file flags can be used; loaded in order.
  • Scope: Values from tfvars apply only to variables declared in the root module.

4. Which Variable Source Wins When Values Conflict?

  1. Environment Variables:
    • TF_VAR_name (OpenTofu honors the same prefix)
  2. terraform.tfvars file
  3. terraform.tfvars.json file (if both this and terraform.tfvars exist, JSON usually overrides for the same variable)
  4. *.auto.tfvars or *.auto.tfvars.json files (loaded alphabetically; later files override earlier ones)
  5. 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_name environment 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 tfvars files.
  • 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**: In variables.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 tfvars with 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 tfvars securely in CI/CD.
    • Use -var-file or environment variables in pipelines.
  • Workspaces (CLI):
    • Use workspace-named tfvars (e.g., dev.tfvars).
    • Load with terraform plan -var-file="${TERRAFORM_WORKSPACE}.tfvars".

9. How Do You Troubleshoot Common tfvars Pitfalls?

  • "Undeclared Variable": Variable in tfvars not declared in .tf files. 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 tfvars doesn't match type in variable declaration.

Remember: Secure your state files, especially when using sensitive variables!

About the author

Sebastian Stadil

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

Terraform tfvars: A Practical Guide to .tfvars Files and Variables

5 articles