🐳

terraform

2 notes  •  Containers & Orchestration

Terraform Command Reference

Essential Terraform commands for managing infrastructure as code.

Core Workflow

# Initialize — download providers and modules
terraform init

# Preview changes
terraform plan

# Apply changes
terraform apply

# Destroy resources
terraform destroy

# Apply without confirmation prompt
terraform apply -auto-approve
terraform destroy -auto-approve

Working with Variables

# Pass variable on command line
terraform apply -var="region=us-east-1"

# Use a variables file
terraform apply -var-file="terraform.tfvars"

# Enable verbose logging
export TF_LOG=TRACE
terraform apply

# Disable verbose logging
export TF_LOG=

Run from Any Directory

# -chdir changes to the specified directory before running
terraform -chdir=/path/to/config apply

State Management

# Show current state
terraform show

# List resources in state
terraform state list

# Show a specific resource
terraform state show aws_instance.web

# Remove a resource from state (without destroying)
terraform state rm aws_instance.web

# Import existing resource into state
terraform import aws_instance.web i-1234567890abcdef0

Workspaces

# Create a new workspace
terraform workspace create staging

# List workspaces
terraform workspace list

# Switch workspace
terraform workspace select production

# Delete a workspace
terraform workspace delete staging

Formatting and Validation

# Format code
terraform fmt

# Validate configuration syntax
terraform validate

# Show output values
terraform output
terraform output <output-name>

Terraform Variable Precedence

When the same variable is defined in multiple places, Terraform applies values in the following order (lowest to highest priority):

Precedence Order (lowest → highest)

  1. Default values in variable blocks in .tf files
  2. Environment variables with the prefix TF_VAR_
  3. terraform.tfvars file (auto-loaded if present)
  4. terraform.tfvars.json file (auto-loaded if present)
  5. *.auto.tfvars or *.auto.tfvars.json files (auto-loaded, alphabetical order)
  6. -var and -var-file command-line flags (highest priority)

Examples

# variable block default (lowest priority)
variable "region" {
  default = "us-west-2"
}

# Environment variable (overrides default)
export TF_VAR_region=us-east-1

# terraform.tfvars (overrides env var)
region = "eu-west-1"

# *.auto.tfvars (overrides terraform.tfvars)
# prod.auto.tfvars:
region = "ap-southeast-1"

# -var flag (highest priority — overrides all)
terraform apply -var="region=sa-east-1"

Best Practice

  • Use terraform.tfvars for default/shared values.
  • Use *.auto.tfvars files for environment-specific overrides (e.g., prod.auto.tfvars, dev.auto.tfvars).
  • Use -var-file in CI/CD pipelines to inject environment-specific values without committing them.
  • Never commit sensitive values — use environment variables or a secrets manager.