How to Use -var Flag in Terraform for Variable Input
Use the
-var flag in Terraform commands to pass variable values directly from the command line, like terraform apply -var='key=value'. This lets you override default or file-based variables without editing configuration files.Syntax
The -var flag syntax is simple: -var='variable_name=value'. You can use it multiple times to set different variables.
This flag overrides variables defined in terraform.tfvars or default values in your configuration.
bash
terraform apply -var='instance_type=t2.micro' -var='region=us-west-2'
Example
This example shows a Terraform configuration using variables and how to pass values with the -var flag during apply.
hcl
variable "instance_type" { description = "Type of AWS instance" type = string default = "t2.small" } provider "aws" { region = "us-east-1" } resource "aws_instance" "example" { ami = "ami-0c55b159cbfafe1f0" instance_type = var.instance_type } # Command to apply with -var flag: # terraform apply -var='instance_type=t2.micro'
Output
Apply complete! Resources: 1 added, 0 changed, 0 destroyed.
Common Pitfalls
- Forgetting to quote the
key=valuepair can cause shell errors. - Using the wrong variable name will not override the intended variable.
- Passing complex types (like maps or lists) requires JSON syntax inside the quotes.
bash
Wrong usage: terraform apply -var=instance_type=t2.micro Correct usage: terraform apply -var='instance_type=t2.micro'
Quick Reference
| Flag | Description | Example |
|---|---|---|
| -var | Set a single variable value | terraform apply -var='name=value' |
| -var-file | Load variables from a file | terraform apply -var-file=custom.tfvars |
| Multiple -var | Set multiple variables | terraform apply -var='a=1' -var='b=2' |
Key Takeaways
Use -var='key=value' to override variables directly from the command line.
Always quote the variable assignment to avoid shell parsing errors.
You can pass multiple -var flags to set several variables at once.
The -var flag overrides default and file-based variable values.
For complex variable types, use JSON syntax inside the quotes.