← All cheatsheets

IaC

Terraform — the daily commands + good-defaults patterns

## Lifecycle
`terraform init` — pull providers + set up backend
`terraform plan` — preview changes
`terraform plan -out=plan.tfplan` — save plan (then apply only that plan)
`terraform apply` — apply changes (use `-auto-approve` only in CI)
`terraform destroy` — tear down (careful)

## Inspect state
`terraform state list` — list resources in state
`terraform state show <addr>` — read one resource
`terraform output` — show outputs
`terraform show plan.tfplan` — render a saved plan

## Surgical fixes
`terraform import <addr> <id>` — bring an existing resource into state
`terraform state rm <addr>` — drop from state without destroying
`terraform state mv <src> <dst>` — rename / move within state
`terraform taint <addr>` — mark for recreate on next apply (deprecated in newer; use `-replace=<addr>` with plan/apply)

## Modules + workspaces
`terraform get -update` — refresh modules
`terraform workspace new <name>` / `terraform workspace select <name>`

## Good defaults
- Always pass `-out=tfplan` in CI so apply applies the same plan you reviewed
- Pin provider versions in `required_providers`
- Use remote backend (S3 + DynamoDB lock, Terraform Cloud, GCS) — never local state for shared infra