- Define variables in a dedicated file
- Reference them in resource blocks
- Override defaults at runtime
- Understand OpenTofu’s variable precedence
Table of Contents
- Defining Variables
- Referencing Variables
- Example: Local File & Random Pet
- Example: AWS EC2 Instance
- Overriding Variable Values
- Variable Precedence
- Links and References
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).description(optional): clarifies its purposedefault: used when no other value is suppliedtype(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 withvar.<name> references:
When referencing variables, do not wrap
Correct:
Incorrect:
var.name in quotes.Correct:
filename = var.filenameIncorrect:
filename = "var.filename"length = "2") and re-run tofu apply.
Example: AWS EC2 Instance
Use variables to configure cloud resources just as easily: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):- Environment variables (
TF_VAR_name) - terraform.tfvars
- .auto.tfvars / .auto.tfvars.json (alphabetical)
- -var-file
- -var flags
instance_type will be t2.medium, since -var overrides all others.