tfvars Files
Store variable values in .tfvars files to keep configuration and values separate.
terraform apply -var-file=prod.tfvarsA .tfvars file holds the values for your input variables, keeping them out of the main configuration. This is how you reuse one codebase across dev, staging, and prod.
Automatic loading
Terraform automatically loads terraform.tfvars and any file ending in .auto.tfvars. Other files are passed with -var-file.
Environment separation
Keep a dev.tfvars and a prod.tfvars and choose one at apply time.
Example
# prod.tfvars
instance_type = "t3.large"
region = "us-east-1"
availability_zones = ["us-east-1a", "us-east-1b", "us-east-1c"]
db_config = {
engine = "postgres"
instance_class = "db.r6g.large"
multi_az = true
}When to use it
- A team keeps a terraform.tfvars file in their repository for shared default values, and each engineer creates a local.tfvars that is gitignored for personal overrides.
- A CI pipeline uses -var-file=prod.tfvars and -var-file=secrets.tfvars to separate environment settings from credentials without mixing them into one file.
- An operator creates staging.tfvars and production.tfvars with different instance sizes and applies the correct one with terraform apply -var-file=production.tfvars.
More examples
Basic terraform.tfvars file
A terraform.tfvars file is picked up automatically by Terraform, setting variable values without any -var-file flag.
# terraform.tfvars — loaded automatically
instance_type = "t3.small"
region = "eu-west-1"
common_tags = {
Project = "my-app"
Environment = "staging"
}Environment-specific var files
Shows environment-specific .tfvars files applied with -var-file to switch configurations without editing .tf files.
# prod.tfvars
# instance_type = "m5.large"
# min_capacity = 3
# Apply with the production values
terraform apply -var-file=prod.tfvars
# Apply with staging values
terraform apply -var-file=staging.tfvarsGitignore sensitive tfvars
Keeps sensitive variables in a gitignored secrets.tfvars and applies it alongside a committed common.tfvars.
# .gitignore
secrets.tfvars
*.tfvars.json
# secrets.tfvars (never committed)
# db_password = "super-secret-value"
# api_key = "abc123"
# Apply combining public and secret vars
terraform apply -var-file=common.tfvars -var-file=secrets.tfvars
Discussion