What is terraform.tfvars?
terraform.tfvars stores variable values separately from the variable declarations. Terraform loads it automatically.
Flow
terraform.tfvars (values)
↓
variables.tf (declarations)
↓
main.tf (usage via var.*)
Example
variables.tf
variable "bucket_name" {}
variable "instance_type" {}terraform.tfvars
bucket_name = "venkat-demo-bucket"
instance_type = "t3.micro"main.tf
resource "aws_s3_bucket" "demo" {
bucket = var.bucket_name
}
resource "aws_instance" "example" {
ami = "ami-0db56f446d44f2f09"
instance_type = var.instance_type
}Override on the command line
terraform apply -var="instance_type=t3.medium"For that run, Terraform uses t3.medium instead of the tfvars value.
Custom var files
Keep environment-specific values in separate files:
dev.tfvars
prod.tfvars
Apply with:
terraform apply -var-file="dev.tfvars"Add *.tfvars with secrets to .gitignore, or use a secrets manager. Never commit production access keys.
The flag is -var=... or -var-file=... — not apply-var.