Skip to main content
Replacing hardcoded values with input variables in OpenTofu (a drop-in replacement for Terraform) makes your infrastructure code more modular, configurable, and reusable. In this guide, you’ll learn how to:
  • Define variables in a dedicated file
  • Reference them in resource blocks
  • Override defaults at runtime
  • Understand OpenTofu’s variable precedence
This approach applies to any provider—from local files to AWS EC2 instances—so you can eliminate literal strings and numbers scattered across your configuration.

Table of Contents


Defining Variables

Best practice is to keep all variable definitions in variables.tf (you can also place them alongside resources in main.tf, but separation improves readability).
Each block names the variable and can include:
  • description (optional): clarifies its purpose
  • default: used when no other value is supplied
  • type (optional): for stricter validation (e.g., string, number, list(string))
Do not store sensitive credentials (like passwords or API keys) in default. Use environment variables, a secure vault provider, or encrypted files instead.

Referencing Variables

In your main.tf, replace literal values with var.<name> references:
When referencing variables, do not wrap var.name in quotes.
Correct: filename = var.filename
Incorrect: filename = "var.filename"
Apply these changes:
If you need different defaults, edit variables.tf (for example, set length = "2") and re-run tofu apply.

Example: AWS EC2 Instance

Use variables to configure cloud resources just as easily:
You can still override these at apply time without changing the file.

Overriding Variable Values

OpenTofu supports four primary ways to supply or override variable values:

Variable Precedence

When the same variable is defined multiple times, OpenTofu applies them in this order (lowest → highest):
  1. Environment variables (TF_VAR_name)
  2. terraform.tfvars
  3. .auto.tfvars / .auto.tfvars.json (alphabetical)
  4. -var-file
  5. -var flags
Example scenario:
The final instance_type will be t2.medium, since -var overrides all others.

Watch Video