AWS & Terraform Cheat Cards

Scan references, not study notes. Commands, tables, the gotcha, the docs path. Built from a $20/month lab account in eu-west-1 — every resource here was created, broken and destroyed by hand before it earned a line.

ASKED — the interview question this card answers. BILLS — this card creates things that cost money; read the teardown before the build. Cards 00–06 are the AWS primitives, 07–12 are Terraform, 13–14 are containers.

00 — The object graph

A1 · A3 · A8Read first

Network — what contains what, and what only points at what

the internet internet gateway attached VPC ivx-lab-vpc · 10.0.0.0/16 route table 0.0.0.0/0 → igw 10.0.0.0/16 → local default route associated associated ivx-lab-public-a 10.0.1.0/24 · eu-west-1a t3.micro + ENI SG (NIC) NACL — subnet edge, stateless ivx-lab-public-b 10.0.2.0/24 · eu-west-1b empty — the second AZ exists so a load balancer can be added later
Containment is half the story. A subnet is public only because a route table associated with it carries a default route to an internet gateway attached to the VPC — three objects, three separate API calls, and the one that silently goes missing is the route.

IAM — three objects and two gates between a policy and a box

trust policy ec2.amazonaws.com gate 1 — who policy s3-readonly-lab gate 2 — what role ivx-ec2-s3-reader holds instance profile not the role assign instance ivx-lab-box no keys on disk IMDSv2 ASIA… + SessionToken, ~1 h
Two gates, not one: the trust policy decides who may become the role, the attached policy decides what it may then do. Admin rights do not override a trust policy. The instance profile is a third object that happens to share the role's name — the console creates it invisibly, the CLI does not.

Create order — dependencies first

 1  VPC                 create-vpc
 2  subnets ×2          create-subnet                one AZ each
 3  public IPs          modify-subnet-attribute --map-public-ip-on-launch ×2
 4  internet gateway    create-internet-gateway + attach-internet-gateway
 5  route table         create-route-table + create-route + associate-route-table ×2
 6  security group      create-security-group + authorize-security-group-ingress
 7  key pair            create-key-pair > ~/.ssh/key.pem ; chmod 400
 8  IAM                 create-policy, create-role, attach-role-policy,
                        create-instance-profile, add-role-to-instance-profile
 9  S3                  create-bucket (LocationConstraint), versioning, public-access-block
10  AMI id              ssm get-parameters   # never hardcode an ami-
11  instance            run-instances --iam-instance-profile Name=…

Destroy order — dependents first, and nothing cascades

 1  instances           terminate-instances + wait   # an attached ENI blocks the subnet and the SG
 2  object versions     list-object-versions + delete-objects, then the delete markers
 3  bucket              delete-bucket                # refuses while anything is left
 4  key pair            delete-key-pair ; rm the local .pem
 5  role out of profile remove-role-from-instance-profile
 6  instance profile    delete-instance-profile
 7  policy off role     detach-role-policy
 8  role                delete-role
 9  policy              delete-policy
10  security group      delete-security-group        # the default SG dies with the VPC
11  route table         disassociate-route-table ×2, delete-route-table
12  IGW                 detach-internet-gateway, delete-internet-gateway
13  subnets             delete-subnet ×2
14  VPC                 delete-vpc

Gotchas

  • AWS never cascades. Every containment and attachment is unwound by hand. Three of the fourteen steps are detachments, not deletions — role out of profile, policy off role, IGW off VPC.
  • A versioned bucket keeps a delete marker for every deleted object, and those block delete-bucket exactly like objects do. Run the delete loop twice: Versions, then DeleteMarkers.
  • ParamValidation: expected one argument means a shell variable was empty, not that the flag was wrong.
  • IAM is eventually consistent. A role used in the same breath as it was created gets a spurious AccessDenied — wait and retry. Scripts need a sleep; Terraform retries for you.
  • The main route table and the default security group cannot be deleted. They die with the VPC, and a teardown script should expect those two refusals.
  • A half-failed imperative script leaves orphans, and re-running it creates duplicates. This is the entire argument for declarative state.
Docs: docs.aws.amazon.com/vpc/latest/userguide/ · docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use_switch-role-ec2.html

01 — Account bootstrap

Day one

Order — nothing gets created until the budget alarm exists

1. Sign up, Free plan, root MFA immediately
2. Root account: never used again after step 3
3. IAM user <admin-user> + AdministratorAccess + MFA + access key
4. Budget alarm BEFORE any resource
5. CLI profile, then verify

Budget alarm

Billing → Budgets → Create budget → Cost budget
  amount: 20 USD/month
  alerts at 50% / 80% / 100% actual → email
Billing → Preferences → Receive free tier usage alerts

CLI

sudo dnf install awscli2
aws configure --profile ivx          # key, secret, eu-west-1, json
aws sts get-caller-identity --profile ivx
export AWS_PROFILE=ivx

Verify before building anything

aws budgets describe-budgets \
  --account-id $(aws sts get-caller-identity --query Account --output text)
aws iam list-mfa-devices

Gotchas

  • Access keys in a repo = account compromised in minutes. Bots scan GitHub continuously.
  • Billing data is us-east-1 only. Cost Explorer looks empty if you filter by region.
  • Accounts opened after 2025-07-15 have no 12-month EC2 free tier — $100 credits at signup, $20 each for five Console Home tasks. The Free plan account closes at 6 months unless upgraded.
  • Deleting an account's resources is not closing the account. Bills continue.
  • eu-west-1 vs eu-west-2 typo = resources you can't find and don't delete.
Docs: aws.amazon.com/free · awscli.amazonaws.com/v2/documentation/api/latest/reference/

02 — IAM

A2 · A5 · A8

The four nouns

ThingCredentials?Holds policies?Note
Useryes — password / AKIA keysyespermanent identity
Groupnoyesbag of users, no login of its own
Policy—is oneJSON: Allow/Deny × Action × Resource
Roletemporary — ASIA + SessionTokenyes, plus a trust policyassumed, expires ~1h

Permission chain: user → group → attached policy. Break any link and it's AccessDenied.

Policy document

{"Version":"2012-10-17","Statement":[
  {"Sid":"x","Effect":"Allow","Action":"s3:GetObject",
   "Resource":"arn:aws:s3:::bucket/*"}]}
  • Version is the policy language date, always 2012-10-17 — not the policy's own version (VersionId: v1).
  • Managed = has its own ARN, reusable. Inline = embedded, no ARN, dies with the principal.
  • AWS-managed ARN arn:aws:iam::aws:policy/… · yours arn:aws:iam::<acct>:policy/…

A role is TWO documents

trust policy      (AssumeRolePolicyDocument) — WHO may assume it
  Principal: {"Service":"ec2.amazonaws.com"} or {"AWS":"arn:...:user/name"}
permission policy — WHAT it may do, attached normally

ARN shapes

arn:aws:iam::<acct>:user/<name>   # IAM is global, region field empty
arn:aws:s3:::<bucket>             # the bucket    (s3:ListBucket)
arn:aws:s3:::<bucket>/*           # the objects   (s3:GetObject)

Commands

aws sts get-caller-identity                    # WHO AM I. always first
aws iam list-attached-user-policies  --user-name X
aws iam list-groups-for-user         --user-name X
aws iam list-attached-group-policies --group-name X   # managed
aws iam list-group-policies          --group-name X   # inline
aws iam get-policy         --policy-arn A      # metadata -> DefaultVersionId
aws iam get-policy-version --policy-arn A --version-id v1
aws iam create-role --role-name N --assume-role-policy-document file://trust.json
aws iam attach-role-policy --role-name N --policy-arn A
aws iam update-assume-role-policy --role-name N --policy-document file://trust.json
aws sts assume-role --role-arn R --role-session-name test

Gotchas

  • not authorized to perform: sts:AssumeRole usually means the role's trust policy refused you, not that you lack permissions. Misleading wording.
  • Admin (Action: *) does not override a trust policy.
  • IAM is eventually consistent — change a trust policy, assume immediately, get a spurious AccessDenied. Wait ~10s. Bites in Terraform too.
  • IAM never validates that a Resource exists. A typo'd bucket is a silent no-op.
Docs: docs.aws.amazon.com/service-authorization/latest/reference/ for actions per service · Console → IAM → Policies → Visual editor generates clean JSON.

03 — VPC & subnets

A3 · A4 · A10Bills

What makes a subnet public

route table entry: 0.0.0.0/0 → igw-xxxx

# that is the whole answer. not the name, not auto-assign IP

Build one by hand

aws ec2 create-vpc --cidr-block 10.0.0.0/16
aws ec2 create-subnet --vpc-id vpc-x --cidr-block 10.0.1.0/24 \
  --availability-zone eu-west-1a
aws ec2 create-internet-gateway
aws ec2 attach-internet-gateway --vpc-id vpc-x --internet-gateway-id igw-x
aws ec2 create-route-table --vpc-id vpc-x
aws ec2 create-route --route-table-id rtb-x \
  --destination-cidr-block 0.0.0.0/0 --gateway-id igw-x
aws ec2 associate-route-table --route-table-id rtb-x --subnet-id subnet-x
aws ec2 modify-subnet-attribute --subnet-id subnet-x --map-public-ip-on-launch

Getting out from a private subnet

PathCostUse for
NAT gatewayhourly + per GBgeneral outbound internet
Gateway endpointfreeS3, DynamoDB only
Interface endpoint (PrivateLink)hourly + per GBother AWS APIs

Inspect

aws ec2 describe-vpcs --query 'Vpcs[].[VpcId,CidrBlock,IsDefault]' --output table
aws ec2 describe-subnets --filters Name=vpc-id,Values=vpc-x \
  --query 'Subnets[].[SubnetId,CidrBlock,AvailabilityZone]' --output table
aws ec2 describe-route-tables --filters Name=vpc-id,Values=vpc-x

Gotchas

  • A VPC CIDR cannot be changed after creation. You can only add secondary CIDRs. Plan it once.
  • AWS reserves 5 addresses per subnet — a /28 gives you 11 usable, not 16.
  • Subnets are AZ-scoped; VPCs are regional. A subnet never spans AZs.
  • A NAT gateway is roughly $32/month before a byte moves, and it's per-AZ for real HA. This is the most common surprise line on a lab bill.
  • An Elastic IP that isn't attached to anything is billed hourly. Free only while in use.
  • The default VPC comes fully wired with public subnets. Fine for a first launch, wrong for anything you'll show an interviewer.
Docs: docs.aws.amazon.com/vpc/latest/userguide/ — "VPC with public and private subnets" is the reference topology.

04 — Security groups & NACLs

A1

The difference, in one table

Security groupNetwork ACL
Attaches toENI (instance, endpoint, LB)subnet
Statestateful — replies allowed automaticallystateless — replies need their own rule
Rulesallow onlyallow and deny
Evaluationall rules, any match winslowest rule number first, first match wins
Can referenceanother security groupCIDR only
Defaultno inbound, all outboundallow everything both ways

Commands

aws ec2 create-security-group --group-name web --description "web tier" --vpc-id vpc-x
aws ec2 authorize-security-group-ingress --group-id sg-web \
  --protocol tcp --port 443 --cidr 0.0.0.0/0

# the idiomatic pattern: db allows web, by group, not by IP
aws ec2 authorize-security-group-ingress --group-id sg-db \
  --protocol tcp --port 5432 --source-group sg-web

aws ec2 describe-security-groups --group-ids sg-web \
  --query 'SecurityGroups[].IpPermissions'

Gotchas

  • Referencing a security group instead of a CIDR is the answer interviewers want — instances come and go, the group reference survives.
  • Stateless NACLs need an outbound rule for ephemeral ports 1024-65535 or replies are dropped. Outbound works, the answer never arrives.
  • A NACL deny beats any security group allow. NACLs are the blunt instrument — use them for a CIDR block ban, not for app rules.
  • Removing the last inbound rule doesn't remove the group's outbound allow-all. Check both directions.
  • A hang means dropped (security group or NACL). A refused connection means something answered. That distinction finds the layer in seconds.
Docs: docs.aws.amazon.com/vpc/latest/userguide/vpc-security-groups.html · …/vpc-network-acls.html

05 — S3

A7Bills

Two CLIs, on purpose

aws s3 ls s3://bucket/prefix/      # high level: ls cp mv sync rm
aws s3 sync ./dir s3://bucket/dir/
aws s3api get-bucket-policy --bucket b     # low level: everything else

Who can make it public — four layers

LayerCheck
Account Block Public Accessaws s3control get-public-access-block
Bucket Block Public Accessaws s3api get-public-access-block --bucket b
Bucket policyaws s3api get-bucket-policy --bucket b
Object ACL (legacy)aws s3api get-bucket-acl --bucket b

Lock it down

aws s3api put-public-access-block --bucket b \
  --public-access-block-configuration \
  BlockPublicAcls=true,IgnorePublicAcls=true,BlockPublicPolicy=true,RestrictPublicBuckets=true

aws s3api put-bucket-versioning --bucket b --versioning-configuration Status=Enabled
aws s3api put-bucket-encryption --bucket b --server-side-encryption-configuration \
  '{"Rules":[{"ApplyServerSideEncryptionByDefault":{"SSEAlgorithm":"AES256"}}]}'

Gotchas

  • Bucket ARN and object ARN are different resources. s3:ListBucket needs arn:aws:s3:::b; s3:GetObject needs arn:aws:s3:::b/*. Most broken policies are this.
  • Bucket names are globally unique across all AWS accounts — the storage is regional, the namespace is not.
  • A versioned bucket won't delete until every version and delete-marker is purged. aws s3 rb --force misses versions.
  • Egress to the internet is the line item people forget. Storage is cheap; getting data out is not.
  • Incomplete multipart uploads keep billing invisibly. Set a lifecycle rule to abort them after 7 days.
Docs: docs.aws.amazon.com/AmazonS3/latest/userguide/ — "Blocking public access" and "Bucket policy examples".

06 — Cost control

A6The whole card

Where the money actually goes in a lab account

ResourceWhy it bills
NAT gatewayhourly + per GB, whether used or not
Unattached Elastic IPhourly, precisely because it's idle
Detached EBS volumeper GB-month; survives instance termination
Load balancerhourly + capacity units
CloudWatch log groupingestion + storage, forever if retention is unset
RDShourly even when idle; snapshots outlive the instance

Check spend from the CLI

aws ce get-cost-and-usage \
  --time-period Start=$(date +%Y-%m-01),End=$(date -d tomorrow +%Y-%m-%d) \
  --granularity MONTHLY --metrics UnblendedCost

# same, split by service — this is the one that answers "why $300"
aws ce get-cost-and-usage \
  --time-period Start=$(date +%Y-%m-01),End=$(date -d tomorrow +%Y-%m-%d) \
  --granularity MONTHLY --metrics UnblendedCost \
  --group-by Type=DIMENSION,Key=SERVICE

Teardown proof — run before you close the laptop

aws ec2 describe-instances \
  --query 'Reservations[].Instances[?State.Name!=`terminated`].InstanceId'
aws ec2 describe-volumes --filters Name=status,Values=available
aws ec2 describe-addresses --query 'Addresses[?AssociationId==`null`]'
aws ec2 describe-nat-gateways --filter Name=state,Values=available
aws elbv2 describe-load-balancers --query 'LoadBalancers[].LoadBalancerName'

Gotchas

  • Cost Explorer lags up to 24h. A teardown that looks free today can still land tomorrow.
  • Budgets alert, they don't stop anything. Nothing in AWS caps spend by itself.
  • Terraform destroy leaves anything it didn't create — console-made test resources, orphaned snapshots, log groups.
  • Tag every lab resource at creation. Untagged resources can't be found by Cost Explorer and won't be found by you either.
Docs: Billing → Cost Explorer (us-east-1 only) · docs.aws.amazon.com/cost-management/latest/userguide/

07 — Terraform state & backend

Two engineers apply at once

What state actually is

aws_vpc.main   ->  vpc-0ce88a62310ff088b
aws_subnet.a   ->  subnet-087406745b94ed959

A two-column ledger: address → real object ID. Nothing in AWS carries the Terraform address — the mapping exists only here. Terraform matches state to config by address only.

The backend block — a setting of terraform{}, never top level

terraform {
  required_providers { aws = { source = "hashicorp/aws", version = "~> 6.0" } }

  backend "s3" {
    bucket       = "tfstate-eu-west-1"
    key          = "stacks/app/terraform.tfstate"   # object path; 1 bucket, many stacks
    region       = "eu-west-1"
    use_lockfile = true                             # current (TF >= 1.10)
  # dynamodb_table = "tf-locks"                     legacy, deprecated 1.11
  }
}
  • The backend does not read your provider block. If credentials work for plan but init fails, that's why — the backend reads S3 itself.
  • No variables in a backend block. Use -backend-config= or partial config.
  • Never hardcode profile = in a provider or backend — it breaks teammates and CI. Credentials live outside the code.

Commands

NeedCommand
adopt a backend, copy local state upterraform init -migrate-state
re-init after a backend changeterraform init -reconfigure (discards, no copy)
what's trackedterraform state list (data sources appear as data.*)
clear a stale lockterraform force-unlock <LOCK_ID>
wait instead of failing-lock-timeout=5m (not -lock=false)

Locking

  • use_lockfile writes a conditional-write object <key>.tflock next to the state. First writer wins.
  • The second runner is refused, not corrupted: Error acquiring the state lock plus Lock Info — ID, Path, Operation, Who, Created.
  • Legacy DynamoDB table: hash_key = "LockID", attribute { name = "LockID", type = "S" }, billing_mode = "PAY_PER_REQUEST".
  • force-unlock only after confirming the holder is dead. Two live writers = corrupt state.

The bootstrap problem

The bucket that holds state can't live in the config it holds state for. Give it its own directory with local state, a hardcoded region and no variables. Run once.

Gotchas

  • A versioned bucket refuses DeleteBucket → BucketNotEmpty. Lab: force_destroy = true. Prod: lifecycle { prevent_destroy = true } and never destroy it.
  • status = "Enabled" on aws_s3_bucket_versioning — exact string.
  • After -migrate-state the local terraform.tfstate stays on disk, unused. S3 is authoritative.
  • State holds secrets in plaintext. Encrypted bucket, block public access, versioned, never in git.
  • Pipeline order is init → validate → plan. validate needs no credentials but does need init — it loads provider schemas.
Docs: registry.terraform.io → Terraform → Backends → S3 · "Why not local state?" → not shared, no locking, lost with the laptop, secrets in the repo.

08 — count · for_each · dynamic

Most-asked Terraform question

The one rule

for_each for things with an identity — named subnets, buckets, users. count only for N identical copies or an on/off switch.

Addressing — the whole reason it matters

ConstructState addressIterator
count = 3res.name[0] [1] [2] — by positioncount.index
for_each = map/setres.name["key"] — by keyeach.key / each.value
dynamic "label"no address — it's a nested blocklabel.value, or iterator = x → x.value

The index-churn trap

Delete the middle item of a count list of three:

state:   [0]=1a   [1]=1b   [2]=1c
config:  [0]=1a   [1]=1c            <- slid down
         ok       REPLACE   DELETE

=> Plan: 1 to add, 0 to change, 2 to destroy

The same deletion with for_each: 0 to add, 0 to change, 1 to destroy. Keys cannot slide. Adding a key touches nothing that already exists.

Skeletons

resource "aws_subnet" "s" {
  for_each          = var.subnets        # {"eu-west-1a" = "10.0.10.0/24"}
  availability_zone = each.key
  cidr_block        = each.value
}

dynamic "ingress" {
  for_each = [22, 80, 443]
  content {
    from_port = ingress.value
    to_port   = ingress.value
  }
}

for_each makes many resources; dynamic makes many blocks inside one resource. The way to hold it: one module, six callers, each with a different port list.

Gotchas

  • A replacement shows in the add AND destroy columns — never in "to change".
  • count always yields a list → aws_s3_bucket.logs[0].arn even when count is 1.
  • Converting a plain resource to count/for_each breaks every reference to it.
  • Optional resource: count = var.flag ? 1 : 0; read it with one(res.name[*].id) → the value or null.
  • for_each keys must be strings known at plan time — no computed IDs. toset() a list.
  • Security group rules: prefer separate aws_vpc_security_group_ingress_rule + for_each over dynamic ingress — one address per rule instead of a positional blob.
  • from_port == to_port for a single port; a rule is always a range.
Docs: registry.terraform.io → Language → Meta-Arguments · Expressions → dynamic Blocks

09 — lifecycle · depends_on · replace & target

Zero-downtime

The three switches

ArgumentMeaningGotcha
prevent_destroy = truerefuse to delete, ever aborts the entire run — nothing else gets destroyed either. Must be a literal, so no per-env flag
ignore_changes = [attr]stop comparing that attribute bidirectional — your own config edits are ignored too. You've given up managing it
create_before_destroy = trueon replace: build new, then delete old a fixed name gives a duplicate-name error. Use name_prefix
lifecycle {
  prevent_destroy       = true
  create_before_destroy = true
  ignore_changes        = [tags, desired_capacity]
}

Narrow to one map key: ignore_changes = [tags["LastScanned"]]

When to use which

  • prevent_destroy → the state bucket, prod RDS, the lock table.
  • ignore_changes → an attribute another system owns: an autoscaler's desired_capacity, an image tag the pipeline sets, a tag stamped by AWS Backup. Not "stop bothering me".
  • create_before_destroy → zero-downtime replacement. The full interview answer is CBD + name_prefix, plus health checks on the thing taking traffic.

To actually destroy a protected resource

Flip prevent_destroy = false (or delete the block), then destroy. Console deletes and terraform state rm bypass it entirely — it guards accidents, not intent.

Replace and target

terraform plan  -replace=aws_security_group.web   # force replace, no config change
terraform apply -replace=ADDR
terraform apply -target=ADDR                      # ONE resource only
  • -replace means "rebuild this; the config is fine, the thing is broken." It replaced taint.
  • -target is a smell — it applies part of your config, so state no longer matches the whole config and the next plan is noisy. HashiCorp documents it as break-glass. Needing it routinely means bad module boundaries or a missing depends_on.

depends_on

Only for dependencies Terraform cannot see. References are the graph — writing aws_vpc.lab.id already creates the edge, which covers almost every case. Use depends_on when the ordering is real but invisible: an IAM policy must exist before a service assumes the role; a bucket policy before an app writes.

depends_on = [aws_iam_role_policy.app]
Docs: registry.terraform.io → Language → Meta-Arguments → lifecycle / depends_on

10 — Drift & import

Someone changed it in the console

Three sources; a plan is a diff of two of them

CONFIG is the only truth · STATE says which objects to ask about · REALITY is refreshed in at every plan.

plan = refresh state from reality, then diff config against reality. Anything in reality that config doesn't mention, inside a managed attribute, is deleted on the next apply.

Reconcile a hand-change — three moves

MoveCommandMeaning
Revertterraform applyconfig is law, stomp it
Adoptedit the .tf to match, then applytheir change was right, codify it
Detect onlyterraform plan -refresh-onlyreport, touch nothing

Reading -refresh-only against a normal plan

normal plan-refresh-only
headerwill be updated in-placehas changed
arrowsreality → configstate → reality (reversed)
changes infrayesnever

apply -refresh-only writes drift into state only — the next normal plan still reverts it. It never resolves drift. Run it on a CI schedule to catch console cowboys.

Tags are a managed map

All-or-nothing. A key missing from config gets - key = ... -> null, i.e. deleted. tags_all = tags plus the provider's default_tags; computed, never written by you.

import — the modern form (TF >= 1.5)

import {
  to = aws_s3_bucket.imported
  id = "bucket-name"
}
terraform plan -generate-config-out=generated.tf   # Terraform writes the HCL for you
terraform apply                                    # "1 to import"
terraform plan                                     # must say: no changes

Then delete the import block — it's a one-time instruction, not permanent config. Generated config is experimental: review and trim before committing.

import — legacy CLI

terraform import aws_s3_bucket.imported bucket-name

The block is plan-first, writes the HCL, lives in git and is CI-safe. The CLI mutates state immediately, you write the HCL yourself, and it has to be re-run by hand in every environment.

Gotchas

  • A plain plan with an import block but no resource block → resource has no configuration.
  • Clean-import proof is plan saying no changes — state and config both match reality.
  • Import brings one object. Bucket policy, versioning, SG rules each need their own.
  • The ID format is per-resource and always a lookup: the registry page's "Import" section.
Docs: registry.terraform.io → the resource page → Import · -generate-config-out is the honest answer to "I can't write HCL from a blank page".

11 — State ops: moved, state mv, state rm

Refactor without destroying

Three categories of command

CommandsTouches AWS?Touches state?
Enforceapply, destroyyesyes
Bookkeepingstate mv, state rm, import, apply -refresh-onlynoyes
Readplan, show, state list, validatenono

plan proposes · apply enforces.

Rename a resource without destroying it

moved {
  from = aws_vpc.lab
  to   = aws_vpc.main
}

Rename the label, fix every reference, add the block, plan → 0 to add, 0 to change, 0 to destroy. Without it, a pure text edit costs you 2 to add and 2 to destroy, because Terraform matches by address and the old address is now an orphan.

Move into a module

The address gains a prefix: module.<call>.<type>.<name>

moved {
  from = aws_vpc.main
  to   = module.network.aws_vpc.main
}
  • A new module source means terraform init again.
  • A module declares no provider and no backend — but yes to terraform { required_version, required_providers }.
  • One moved per resource. Keep the blocks until every environment has applied, then delete them.

moved block against terraform state mv

The block applies after a reviewed plan, lives in git, and every workspace picks it up; undo is deleting it. The CLI is immediate, unplanned, invisible in review, and must be re-run by hand in each environment. "I refactor state declaratively so the change is reviewable" is the interview line.

state rm — forget without destroying

Legitimate when handing a resource to another repo or team. If config still declares it, three outcomes:

  • Collision — InvalidSubnet.Conflict, apply fails. The loud, harmless one.
  • Silent duplicate — anything with a generated name: a second object, billed twice.
  • Orphan — destroy only destroys rows in state. Nothing will ever clean it up. This is how a forgotten NAT gateway bills $35/month forever.

Recover with import, then plan must say no changes.

Docs: registry.terraform.io → Language → moved blocks · CLI → State → state mv/state rm

12 — Multi-env & linting

How do you keep dev and prod apart?

Layout — separate directories, one shared module

tf-multi-env/
  bootstrap/          state bucket, LOCAL state, run once
  modules/network/    main.tf variables.tf outputs.tf versions.tf
  envs/dev/main.tf    backend key envs/dev/terraform.tfstate
  envs/prod/main.tf   backend key envs/prod/terraform.tfstate

Dev and prod differ in about four lines: the state key and the values. The logic lives once, in the module.

The boundary is the state key

envs/dev/terraform.tfstate    module.network.aws_vpc.this -> vpc-053...
envs/prod/terraform.tfstate   module.network.aws_vpc.this -> vpc-0b1...

The addresses are identical in both environments. Two ledgers, same left column, different right column. Point both directories at the same key and the second apply rewrites the first environment's right column — and then mutates its real infrastructure.

What belongs in a module

BlockIn a module?
provider "aws" { region = ... }No — inherited from the root
backend "s3"No — only roots have state
terraform { required_version, required_providers }Yes, expected

The module is permissive (>= 6.0); the root pins (~> 6.0).

Linters

tflint --init          # once, downloads the plugin
tflint --recursive     # silence = pass
trivy config <dir>     # tfsec is ARCHIVED, folded into trivy

.tflint.hcl at the repo root: config { call_module_type = "all" } plus the terraform and AWS plugins, pinned.

ToolCatches
terraform validatesyntax and types
tflintreal AWS API facts, dead code, missing blocks
trivy configsecurity posture

Triage, not zero findings

  • Fix: "no customer-managed key" on a state bucket. State holds plaintext secrets, and a key policy separates "can read the bucket" from "can decrypt the state". About $1/month per key.
  • Context: SSE-S3 (AES256) has been on by default since January 2023, so "unencrypted" wording in a finding is misleading.
  • Accept: map_public_ip_on_launch = true on a subnet named public. That's the design.

Nobody ships zero findings. Being able to say which you fixed and which you accepted, and why, is the actual skill.

Docs: github.com/terraform-linters/tflint · trivy.dev → Misconfiguration Scanning

13 — ECR

Tags against digests500 MB free

Commands

aws ecr create-repository --repository-name X --image-tag-mutability IMMUTABLE
aws ecr get-login-password | docker login --username AWS --password-stdin \
    <acct>.dkr.ecr.<region>.amazonaws.com
aws ecr describe-images --repository-name X \
    --query 'imageDetails[].[imageDigest,imageTags]' --output text
aws ecr put-lifecycle-policy --repository-name X --lifecycle-policy-text file://lifecycle.json
aws ecr start-lifecycle-policy-preview   # = plan, but for deletions
aws ecr delete-repository --repository-name X --force

The one idea that matters

A tag is a mutable pointer; the digest is the content. Re-push the same tag and the old digest is orphaned — still stored, still billed, still pullable by digest. That's why pipelines tag by git SHA and why task definitions pin @sha256:....

Gotchas

  • The login token lives 12 hours. It is your IAM identity traded for a docker password.
  • One docker push writes three entries: image.index (the tagged one), image.manifest, and attestation.manifest. --provenance=false drops the third.
  • IMMUTABLE rejects the tag write only — the blobs upload first, then you get the error.
  • Lifecycle policy selection keys: tagStatus · countType (imageCountMoreThan | sinceImagePushed) · countUnit · countNumber. Production default: untagged, 14 days.
  • In Terraform, aws_ecr_repository needs force_delete = true or destroy fails while images are present — the same shape as a versioned bucket.
  • Docker Desktop's credsStore: desktop gives pass not initialized. The real fix is docker-credential-ecr-login.
Docs: docs.aws.amazon.com/AmazonECR → Lifecycle policies · Pushing from CI is on the CI/CD cards.

14 — ECS Fargate & ALB

Walk me through a deployALB ~$0.0225/hr

Read this first — the Kubernetes pivot

ECSKubernetes
clustercluster (no compute of its own, free)
serviceDeployment — desired count, self-heals
taskPod — own ENI, own public IP
task definitionPodSpec — immutable, revision :1, :2…
ALB + target groupIngress + Endpoints
execution rolekubelet pulling the image + imagePullSecret
task roleServiceAccount / IRSA — your code's identity

Task definition gotchas

  • cpu and memory are strings: "256" / "512".
  • networkMode: "awsvpc" is mandatory; requiresCompatibilities: ["FARGATE"].
  • Pin image by digest, not tag.
  • executionRoleArn is needed even for public images — log delivery goes through it. Managed policy AmazonECSTaskExecutionRolePolicy, trust principal ecs-tasks.amazonaws.com.
  • assignPublicIp: ENABLED in a public subnet is the no-NAT path. A private subnet needs a NAT gateway ($35/month) or VPC endpoints (~$7/month each).
  • There is no service IP: service → task → attachments[].details[?name=='networkInterfaceId'] → describe-network-interfaces → Association.PublicIp. That chain is exactly what the load balancer exists to remove.

ALB in front of Fargate

ALB objectKubernetes
load balancerthe ingress controller's LB
listener :80Ingress port; a listener rule is an Ingress rule
target groupService + Endpoints
target_type = "ip"Pod IPs — required for Fargate
health_checkreadinessProbe
  • Chain the security groups. ALB SG takes :80 from your address; the task SG takes :8080 with referenced_security_group_id = <alb sg>. Identity, not address — the same distinction as a NetworkPolicy podSelector against an ipBlock.
  • Modern rules are aws_vpc_security_group_ingress_rule / _egress_rule, one resource per rule.
  • The service's load_balancer{} needs target_group_arn, container_port, and a container_name that matches the task definition's container name — a typo hangs the deploy with a useless error.
  • depends_on = [aws_lb_listener.http] — the listener must exist before targets register.
  • deregistration_delay defaults to 300 s, so a destroy waits about five minutes. 30 in a lab; keep 300 in production.
  • 503 = the ALB is up with no healthy target. Timeout = a security group. Expect ~60 s of 503 after a new task: healthy_threshold 2 × interval 30.
  • Rolling deploy with a new digest: the task definition is immutable so it is replaced (-/+), while the service updates in place (~) to point at the new revision.
  • ECR and infrastructure are two lifecycles. A fresh apply makes an empty repository and the task cannot pull until something pushes. Fix with a bootstrap stack, or have the pipeline push before deploying.

Teardown order, by hand

service --force → task reaches STOPPED (DRAINING blocks everything) → cluster → ENI released → security group → role → log group → repository. ClusterContainsTasksException and DependencyViolation both mean you were too early. terraform destroy walks this graph for you — which is most of the argument for building it in Terraform in the first place.

Docs: docs.aws.amazon.com/AmazonECS → Fargate · registry.terraform.io → aws_ecs_service, aws_lb_target_group

Related: CI/CD cheat cards · CKA cheat cards · CKS cheat cards · DevOps interview bank