Terraform Cheatsheet
Top commands.
Initialisation
terraform init: downloads providers and modules; sets up backend. Run once per project, again after backend changes.
terraform init -upgrade: refreshes provider versions to latest matching constraints. Use intentionally; pin versions.
terraform init -reconfigure: forces backend reinitialisation. Used when migrating state.
Plan and apply
terraform plan -out=plan.tfplan: saves the plan to a file. Apply that exact plan to ensure no drift between plan and apply.
terraform apply plan.tfplan: applies the saved plan.
terraform plan -destroy: shows what would be destroyed. Sanity-check before terraform destroy.
State management
terraform state list: lists resources in state. Useful for finding what's tracked.
terraform state rm aws_instance.foo: removes from state without destroying. Common when refactoring or importing.
terraform import aws_instance.foo i-1234: imports an existing resource into state. Useful for adopting hand-created infrastructure.
Workspaces
terraform workspace list: lists workspaces. Each is a separate state file.
terraform workspace new staging: creates and switches to a new workspace.
Workspaces are useful for environment separation but inferior to per-environment directories for serious use. Workspaces share configuration; directories isolate.
Debugging
TF_LOG=DEBUG terraform plan: verbose output. Useful for provider-level debugging.
terraform refresh: reconciles state with reality. Catches drift between actual cloud state and Terraform's view.
terraform validate: checks config syntax. CI gate before plan.