- 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:| Method | Description | Example |
|---|---|---|
| Prompted Input | Leave out default and answer interactive prompt | hcl\nvariable "ami" {}\nvariable "instance_type" {}\n$ tofu apply |
| CLI Flags | Pass -var flags on the command line | bash\n$ tofu apply \\\n -var "ami=ami-0edab43b6fa892279" \\\n -var "instance_type=t2.micro"\n |
| Environment Variables | Set TF_VAR_<name> in your shell | bash\nexport TF_VAR_ami="ami-0edab43b6fa892279"\nexport TF_VAR_instance_type="t2.micro"\n$ tofu apply\n |
| tfvars Files | Use .tfvars or .tfvars.json files | variables.tfvars:hcl\nami = "ami-0edab43b6fa892279"\ninstance_type = "t2.micro"\n$ tofu apply -var-file=variables.tfvars |
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.