Basic Variable Configuration
variables.tf
variable "region" { description = "AWS deployment region" type = string default = "us-east-1" } variable "instance_type" { description = "EC2 instance type" type = string validation { condition = contains(["t2.micro", "t3.small", "c5.large"], var.instance_type) error_message = "Unsupported instance type selected" } }
Define variable schema with types and validation rules
terraform.tfvars
region = "us-west-2" instance_type = "t3.small"
Set default values in auto-loaded terraform.tfvars
Environment-Specific Configuration
dev.tfvars
project_name = "my-service-dev" instance_type = "t3.micro" count = 2
Used for development testing with lightweight resources
prod.tfvars
project_name = "my-service-prod" instance_type = "c5.xlarge" count = 4 backup_enabled = true
Production configuration with optimized resources
Use terraform apply -var-file=prod.tfvars
to specify environment
Sensitive Values Handling
secrets.tfvars
aws_access_key = "AKIAXXXXXXXXXXXXXXXX" aws_secret_key = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
Never commit this file to source control. Store in secure environments.
⚠️ Alternative: Use TF_VAR_
environment variables instead
Command Line Integration
terraform apply \ -var "ami_id=ami-abc123xyz" \ -var "tags={ Env = "testing" }"
Pass individual values directly at execution time
terraform apply \ -var-file=eu-west-1.tfvars \ -var-file="prod-credentials.auto.tfvars"
Load multiple files for environment-specific configurations
*.auto.tfvars files are automatically loaded