Terraform CLI Cheatsheet
Core Workflow
terraform init
terraform plan
terraform apply
terraform destroy
State Management
terraform state list
terraform state show aws_instance.web
terraform state mv aws_instance.old aws_instance.new
terraform state rm aws_instance.web
terraform state pull
terraform state push
Workspaces
terraform workspace list
terraform workspace new staging
terraform workspace select production
terraform workspace show
Import & Output
terraform import aws_instance.web i-abc123
terraform output
terraform output vpc_id
terraform fmt
terraform fmt -recursive
terraform validate
Planning Options
terraform plan -out=tfplan
terraform apply tfplan
terraform plan -var-file=prod.tfvars
terraform plan -target=aws_instance.web
terraform plan -destroy
Modules
terraform get
terraform get -update
terraform init -upgrade
Debugging
TF_LOG=DEBUG terraform plan
TF_LOG=TRACE terraform apply
TF_LOG=DEBUG TF_LOG_PATH=./debug.log terraform plan
Useful Flags
| Flag |
Description |
-auto-approve |
Skip interactive approval |
-parallelism=N |
Limit parallel operations (default 10) |
-refresh=false |
Skip state refresh |
-lock=false |
Disable state locking |
-no-color |
Disable color output |
-compact-warnings |
Show compact warning output |
Backend Configuration
# S3 backend example
terraform {
backend "s3" {
bucket = "my-tfstate"
key = "prod/terraform.tfstate"
region = "us-east-1"
dynamodb_table = "terraform-locks"
encrypt = true
}
}
Variable Precedence (lowest to highest)
- Default values in code
terraform.tfvars
*.auto.tfvars
-var-file flag
-var flag
- Environment variables
TF_VAR_*