Skip to main content

Terraform cheatsheet

A one-page reference for Terraform. For state internals, modules, and the full AWS worked example, see the complete guide.

๐Ÿ“– Full guide: Terraform โ†’ Intermediate
Learn this in 5 minutes5 min
  1. Begin with the Core workflow card
  2. Then the Safer apply and HCL basics cards
  3. Treat the other 5 cards as lookups โ€” scan by card title when you need one
  4. Open the full guide when a card isn't enough

Core workflowโ€‹

terraform init            # download providers/modules, init backend
terraform plan # read-only diff: what would change
terraform apply # execute the plan
terraform destroy # tear down everything in state

Always read the plan before applying โ€” it's the primary safety mechanism.

Safer applyโ€‹

terraform fmt -recursive
terraform validate
terraform plan -out=tfplan
terraform apply tfplan # applies exactly what was reviewed

HCL basicsโ€‹

resource "aws_instance" "web" {
ami = "ami-123456"
instance_type = "t3.micro"
tags = { Name = "web" }
}

variable "region" { default = "us-east-1" }
output "public_ip" { value = aws_instance.web.public_ip }

Stateโ€‹

terraform state list
terraform state show aws_instance.web
terraform state mv <old> <new>
terraform import aws_instance.web i-0123456

Remote state (S3 + DynamoDB lock, or Terraform Cloud) is mandatory for team use.

Modulesโ€‹

module "vpc" {
source = "./modules/vpc"
cidr = "10.0.0.0/16"
}

Modules are the unit of reuse โ€” pin versions for remote modules to avoid surprise drift on init.

Workspaces vs. directory-per-envโ€‹

terraform workspace new staging
terraform workspace select staging

Workspaces share the same config with different state; directory-per-env gives full config isolation. Most teams prefer directory-per-env at scale.

Drift & importโ€‹

terraform plan -refresh-only   # detect drift without changing config
terraform import <resource> <id>

Drift = real infra changed outside Terraform. Detect regularly; import existing resources rather than recreating them.

Common pitfallsโ€‹

  • No remote state / no locking โ†’ concurrent applies corrupt state.
  • Hardcoded values instead of variables โ†’ no reuse across envs.
  • -target used habitually instead of for genuine emergencies.
  • Secrets committed in .tf files instead of a secrets manager.
See: Common Pitfalls