Loading...
Cheat sheet
Core workflow, state management, workspaces, import, and debugging.
# Initialise (download providers & modules)
terraform init
# Preview changes
terraform plan
# Preview and save plan
terraform plan -out=tfplan
# Apply saved plan
terraform apply tfplan
# Apply directly (skips interactive approval)
terraform apply -auto-approve
# Destroy all managed resources
terraform destroy# List resources in state
terraform state list
# Show a specific resource
terraform state show aws_instance.web
# Move resource to new address
terraform state mv \
aws_instance.web \
module.compute.aws_instance.web
# Remove resource from state (orphan it)
terraform state rm aws_instance.legacy
# Pull remote state to stdout
terraform state pull
# Force-unlock a stuck state
terraform force-unlock <lock-id># Import existing resource into state
terraform import aws_s3_bucket.logs my-log-bucket
# Generate config for resources declared in import {} blocks (v1.5+)
terraform plan -generate-config-out=generated.tf
# Replace a specific resource (force recreate)
terraform apply -replace="aws_instance.web"
# Target a specific resource
terraform apply -target="module.eks"
terraform plan -target="aws_security_group.allow_http"# List workspaces
terraform workspace list
# Create a new workspace
terraform workspace new staging
# Switch workspace
terraform workspace select production
# Show current workspace
terraform workspace show
# Delete a workspace
terraform workspace delete staging# Pass variable on CLI
terraform apply -var="region=eu-west-1"
# Load from var file
terraform apply -var-file="prod.tfvars"
# Variable precedence (highest wins):
# 1. -var and -var-file flags (evaluated left-to-right on CLI)
# 2. *.auto.tfvars / *.auto.tfvars.json (lexical order)
# 3. terraform.tfvars.json
# 4. terraform.tfvars
# 5. TF_VAR_* environment variables
# Show outputs
terraform output
terraform output vpc_id# Format all .tf files
terraform fmt -recursive
# Check formatting (exit 1 if diff)
terraform fmt -check -recursive
# Validate configuration
terraform validate
# Upgrade providers to latest in lock file
terraform init -upgrade
# Show provider requirements
terraform providers# Verbose logging
TF_LOG=DEBUG terraform plan
# Log levels: TRACE, DEBUG, INFO, WARN, ERROR
# Log to file
TF_LOG=DEBUG TF_LOG_PATH=./tf.log terraform apply
# Show dependency graph (requires graphviz)
terraform graph | dot -Tsvg > graph.svg
# Refresh state without applying changes (preferred — shows diff before writing)
terraform plan -refresh-only
terraform apply -refresh-only
# terraform refresh is deprecated since v1.5