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: tfvars files 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):
    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. Variable Precedence (Lowest to Highest)

  1. Environment Variables:
    • TF_VAR_name
    • OPENTOFU_VAR_name (takes precedence over TF_VAR_ if both set for OpenTofu)
  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. 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_ but OPENTOFU_VAR_name takes precedence if both are set. Recommend using OPENTOFU_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 tfvars files.
  • 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: 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. 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 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. Troubleshooting Common 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!