Terraform Tutorial — tfvars and Environment Variables
There are five ways to provide values for Terraform variables. Understanding the precedence order prevents surprises.
Method 1: terraform.tfvars File
Create a file called terraform.tfvars in your project root:
# terraform.tfvars
region = "us-east-1"
environment = "dev"
instance_type = "t3.micro"
Terraform loads terraform.tfvars automatically — you don’t need to pass any flags.
Method 2: Named .tfvars Files
For environment-specific values, create separate files:
# dev.tfvars
environment = "dev"
instance_type = "t3.micro"
instance_count = 1
# prod.tfvars
environment = "prod"
instance_type = "t3.large"
instance_count = 5
Pass the file explicitly:
$ terraform plan -var-file="dev.tfvars"
$ terraform apply -var-file="prod.tfvars"
Method 3: *.auto.tfvars Files
Any file named *.auto.tfvars or *.auto.tfvars.json is loaded automatically:
# common.auto.tfvars
project_name = "web-app"
team = "backend"
This is useful for values that apply to all environments.
Method 4: -var CLI Flag
Pass individual values on the command line:
$ terraform plan -var="environment=staging" -var="instance_type=t3.small"
Useful for overriding a single value without creating a file.
Method 5: TF_VAR_ Environment Variables
Prefix any environment variable with TF_VAR_ and Terraform reads it:
$ export TF_VAR_region="eu-west-1"
$ export TF_VAR_environment="staging"
$ terraform plan
This is the standard method for CI/CD pipelines where secrets are injected as environment variables.
Precedence Order (Lowest to Highest)
When the same variable is set in multiple places, the highest priority wins:
| Priority | Source | Example |
|---|---|---|
| 1 (lowest) | Default value in variable {} |
default = "us-east-1" |
| 2 | terraform.tfvars |
region = "eu-west-1" |
| 3 | *.auto.tfvars (alphabetical) |
common.auto.tfvars |
| 4 | -var-file flag |
-var-file="prod.tfvars" |
| 5 | -var flag |
-var="region=ap-south-1" |
| 6 (highest) | TF_VAR_ environment variable |
TF_VAR_region=us-west-2 |
💡 Tip: In practice, use
terraform.tfvarsfor common values, environment-specific.tfvarsfiles with-var-file, andTF_VAR_environment variables for secrets in CI/CD.
Common Pattern: Environment-Specific Deploys
# Deploy to dev
$ terraform apply -var-file="environments/dev.tfvars"
# Deploy to staging
$ terraform apply -var-file="environments/staging.tfvars"
# Deploy to production
$ terraform apply -var-file="environments/prod.tfvars"
Each file sets the appropriate values for that environment.
What’s Next?
You know how to provide variable values. Next, let’s add validation to ensure variables contain acceptable values.