IaC review: spotting the faults a reviewer looks for in HCL

Review infrastructure diffs like security changes: what gets destroyed, what becomes public, what loses its backup, and what the blast radius is if this is wrong.

Read the briefing
About 8 min to read 10 drills

What to remember

  1. Destroys and replacements first. A resource replacement in the plan is a deletion with a new name.
  2. Look for 0.0.0.0/0 and wildcard IAM. Two patterns, most of the real findings.
  3. Check retention and deletion protection. reclaimPolicy, deletion_protection, lifecycle rules — a one-line change with permanent consequences.
  4. Ask what happens if this is applied twice. Idempotence is the property that makes automation safe.
  5. Every changed line should trace to the ticket. Drive-by 'improvements' in an infrastructure diff are how unrelated outages happen.

The big picture

IaC review is the skill of reading Terraform the way an operator reads a plan: in blast-radius order, asking what happens when this applies, when it is re-applied by someone else, and when its inputs change. Interview loops use it constantly (a take-home module, a "here is a PR, you have ten minutes" exercise, or a live read of HCL) because it reveals whether you have been burned by the real failure modes: state on a laptop, a plan that is not the plan that applies, a credential in git, a database one -/+ away from deletion, a port open to the world, and identities that churn when a list changes.

The mental model

Review in tiers, each a precondition for the next. Reproducibility first (remote locked state, pinned providers and modules, committed lock file): if these are wrong, the plan you are reading is not the plan that will run, so nothing else is worth judging yet. Then irreversible harm (secrets in code or state, missing destroy guards, unread -/+ lines). Then exposure (0.0.0.0/0, public flags). Then correctness under change (stable keys, data sources over pasted ids). Style last, and mostly automated.

In depth

Review in blast-radius order, and ask for the plan

A linear read of 900 lines in thirty minutes produces naming comments and misses the security group in file six. The senior pattern is triage: mechanically check the highest-severity classes first, because finding one changes whether the rest of the review happens at all.

Tier one is reproducibility: read the terraform {} block and every module source before any resource. Tier two is irreversible harm: grep -nE 'password|secret|token' *.tf *.tfvars, then skip_final_snapshot, deletion_protection, prevent_destroy, force_destroy. Tier three is exposure: 0.0.0.0/0, ::/0, publicly_accessible, acl = "public-read", a missing aws_s3_bucket_public_access_block. Tier four is correctness when inputs change: count over lists, for_each keyed on computed values, hard-coded ids and ARNs. Only then typing, validation blocks, descriptions, tags, naming.

terraform fmt -check and terraform validate passing means the code parses and types agree; neither knows what a security group is. A sandbox apply proves it runs, not that it is safe in production. What you want attached to every PR is terraform plan output (the human summary for people, terraform show -json for machines), because it is the only artifact that shows a -/+ replacement or a destroy of something stateful. "Please attach the plan" is the most valuable review comment in Terraform, and asking for it is a tell interviewers listen for.

Tier one: the terraform block

Three lines decide whether two engineers running the same commit get the same plan.

Backend. No backend, or backend "local", means state lives on one laptop and every teammate's apply diverges. A remote backend without locking is subtler: S3 is durable, but two concurrent applies read the same state serial and the loser's write silently overwrites the winner's, orphaning real resources. Look for dynamodb_table = "..." (or use_lockfile = true on Terraform versions with S3 native locking) and encrypt = true, plus bucket versioning so a bad write can be rolled back, and IAM that restricts the bucket to the CI role and break-glass users.

Provider constraints. source = "hashicorp/aws" with no version resolves the newest release on every fresh init; >= 5.0 is not a pin either. The reviewer wants a pessimistic constraint, version = "~> 5.0" (any 5.x, never 6), and a committed .terraform.lock.hcl, which records the exact version and hashes that init selected so CI and laptops use the same binary until someone deliberately runs init -upgrade. The lock file covers providers only, not modules or the CLI, so required_version still matters.

Module sources. source = "git::https://.../modules.git//vpc?ref=main" runs whatever is on main today; an unrelated merge changes production's plan with no change in this repository. Pin to a tag (?ref=v1.4.2) or a commit SHA, and for registry modules use version = "~> 3.1". The question to keep asking is: if I re-run init and plan in a month with this exact commit, do I get this exact plan?

Tier two: secrets in code and in state

The finding takes many shapes: a default = "Sup3rS3cret!" on a sensitive variable, a committed terraform.tfvars or *.auto.tfvars, a token in a provider block, a user_data script with a password, a local built from a literal. All of them put the credential in git history and in every clone.

sensitive = true changes only what the CLI prints. State stores every attribute in plaintext, so a password passed to aws_db_instance is in the state file whether or not it was marked sensitive, and so is a secret read through data "aws_secretsmanager_secret_version". Protecting state is therefore part of the same finding: encrypted backend, tight IAM, versioning, and no state files in the repository (check .gitignore for *.tfstate*).

The fix has three parts, in order. Rotate the credential, because a committed secret is a leaked secret even after history is rewritten. Get the literal out of code: remove the default and pass the value at apply time (TF_VAR_db_password from the CI secret store, or -var-file from a file that is generated, never committed), or let the provider own it (manage_master_user_password = true on RDS stores the generated password in Secrets Manager and keeps it out of your configuration). Terraform 1.10+ ephemeral values and 1.11+ write-only arguments exist precisely so a secret can pass through a run without landing in plan or state; check the version in use. Then add the mechanism: push protection and secret scanning on the repository, checkov or tfsec in CI, and a rule that variables holding credentials never have defaults.

Tier two: destroy guards on stateful resources

Databases, buckets with data, EBS volumes, and anything else you cannot recreate from code need two independent guards plus a recovery point.

lifecycle { prevent_destroy = true } is a plan-time assertion: any plan that would destroy this address fails, including terraform destroy, a -/+ replacement caused by a force-new argument, and a careless -target. It does not survive deleting the resource block (the lifecycle goes with it), and terraform state rm sidesteps it by orphaning rather than destroying. So pair it with a guard the API enforces regardless of Terraform: deletion_protection = true on RDS, force_destroy = false on S3, disable_api_termination on critical instances. Then keep a recovery point for the day both are deliberately lifted: skip_final_snapshot = false with a final_snapshot_identifier, remembering that RDS automated backups are deleted with the instance, so "we have backups" is not an answer.

The reason this tier matters more than it looks is that destroys hide inside changes. Renaming an identifier, changing an argument the provider marks force-new, or refactoring a resource into a module without a moved block all plan as -/+ destroy and then create replacement, and an apply approved on the summary line 1 to add, 1 to destroy deletes the database. Read every -/+ and # forces replacement comment in the plan, and in CI parse the JSON plan for any delete action on a protected type. The removed block exists for the legitimate case of stopping management without destroying.

Tier three: network exposure

The most common finding in take-homes is an ingress rule on 22, 3389, 5432, 3306, 6379, or 27017 from 0.0.0.0/0, often with a description = "temporary while we debug". The most common defence is "it is in a private subnet". The answer is that the subnet argument describes routing today; a misconfigured peering, a bastion, a compromised pod, or a later public subnet makes the security group the whole perimeter, and security groups are the last hop, so review them as if the network in front had already failed.

What good looks like: ingress from another security group (security_groups = [aws_security_group.app.id]) rather than a CIDR, human access through SSM Session Manager or the VPN's security group, no management ports open to the internet at all. Egress-all is the common default and worth a question for a database tier (why does Postgres need to reach the internet?) but usually not a blocker.

The same tier covers public flags: publicly_accessible = true on RDS, buckets without an aws_s3_bucket_public_access_block, associate_public_ip_address on instances that should not have one, a load balancer with internal = false that was meant to be internal, and IAM policies with Principal: "*". These are also the checks most worth automating: every policy-as-code tool ships rules for them, so a human reviewer's job is to explain why the rule exists when the author pushes back with "temporary".

Tier four: identity under change

A configuration that applies cleanly today can still destroy things the first time an input changes, because Terraform tracks instances by address. count gives positional addresses, so removing bob from ["alice", "bob", "carol"] shifts carol to index 1: Terraform plans a rename of team[1] from bob to carol (bob's access keys now belong to "carol") and destroys team[2]. for_each = toset(var.team_users) gives team["alice"], so removing one key touches one instance.

for_each is only as stable as its key. Keying on a private IP, an ARN, or a generated name means a replaced instance is a "new key" and its dependent record is destroyed and recreated; when the key is not known until apply, plan fails with "keys derived from resource attributes that cannot be determined until apply". Key on the stable, human-chosen identifier and let the volatile value be an attribute: for_each = aws_instance.worker with records = [each.value.private_ip].

Two adjacent checks belong here. Hard-coded ids and ARNs (vpc-0abc..., a KMS key from one account) make a module work in exactly one place; data sources or required inputs make it portable. And when a fix re-addresses existing instances (count to for_each, a rename, a move into a module), the PR must carry moved blocks (or a state mv runbook) or the fix itself becomes the destroy it was meant to prevent. Reviewers who ask "what does the plan look like the first time someone removes an element?" catch this class; validate never will.

Myths and facts

Myth: terraform validate passing means the module is safe to apply.

Fact: validate checks syntax, references, and types. It knows nothing about open security groups, missing destroy guards, unpinned sources, or secrets; only a human or a policy engine reading the plan does.

Myth: sensitive = true protects the credential.

Fact: It redacts CLI output only. The literal stays in git history and the value is written to state in plaintext; the fix is to remove the literal, protect state, and rotate.

Myth: A private subnet makes an open security group harmless.

Fact: Routing changes silently and the rule does not; security groups are the last hop and are reviewed as if the network in front had failed.

Myth: prevent_destroy alone protects the database.

Fact: It fails plans that include a destroy, but deleting the resource block or state rm bypasses it. Pair it with an API-level guard (deletion_protection) and a final snapshot.

Myth: >= 5.0 pins the provider.

Fact: It is open-ended and admits every future major. ~> 5.0 allows 5.x only, and the committed lock file fixes the exact version until init -upgrade.

Myth: A plan that shows 1 to add, 1 to destroy is a small change.

Fact: That is the summary of a replacement. Read the -/+ block and the # forces replacement comment; for a database it is a deletion.

How pros do it

  • Read the terraform {} block, provider constraints, and module sources before any resource; if the plan is not reproducible, stop and request changes.
  • Require terraform plan output (and the JSON plan for tooling) on every PR, and read every -/+ and # forces replacement line before approving.
  • Block on any credential-shaped literal in .tf, .tfvars, or defaults; require rotation as part of the fix, not just removal.
  • Insist on both guards for stateful resources: prevent_destroy in lifecycle and the provider's deletion protection, plus skip_final_snapshot = false with a named final snapshot.
  • Treat 0.0.0.0/0 on management or database ports as a blocker regardless of subnet placement; admit tiers by security-group reference and humans via SSM or VPN.
  • Prefer for_each keyed on human-chosen names over count or computed keys, and require moved blocks whenever a fix re-addresses existing instances.
  • Automate tiers one to three with policy-as-code in CI (tfsec or checkov plus OPA or Sentinel rules for team conventions) so human review time goes to design.

Questions people ask

Where do I even start when the PR is 900 lines and I have thirty minutes?

Say 'not at line one' and give the order: read the terraform {} block and every module source, grep for secrets and 0.0.0.0/0, grep for skip_final_snapshot and deletion_protection, then ask for the plan output. Explain why the order is the answer: the highest-severity findings take minutes to check mechanically, and finding one changes whether the rest of the review happens at all.

How do I tell whether a plan will delete something important?

Point at the plan, not the HCL: -/+ blocks and # forces replacement comments, and any - resource on a stateful type; say that the summary line counts a replacement as one add and one destroy, so 1 to add, 1 to destroy can be the database. Then the mechanism: in CI, parse terraform show -json for delete in resource_changes[].change.actions and fail on protected types.

The author says the open SSH rule is temporary. Can I approve with a follow-up?

No, and give the reason as an audit statement: an approval is a record saying this was acceptable, and 'temporary' rules are how permanent holes are born. Request changes with the concrete fix (SSM Session Manager or the VPN's security group) so the answer is fast rather than shorter.

Is sensitive = true on the variable enough if the default is only a placeholder?

No. Separate display from storage: sensitive changes what the CLI prints; a default that looks like a credential is in git history and will be in state in plaintext. Give the fix in order: rotate if it was ever real, remove the default, supply the value at apply time or let the provider manage it.

Why does removing one name from a list plan changes to resources I did not touch?

Diagnose it in one sentence: the resource uses count, so instances are addressed by position and the list edit renumbered them. Then the fix with its own guard: switch to for_each over a set of names, and migrate the existing instances with moved blocks so the switch itself does not destroy anything.

The take-home applies cleanly in my sandbox. Why would a reviewer still reject it?

Say what a green apply proves: it runs once, for you, today. Then list what review asks instead: what happens when a teammate runs it (state, pinning), when someone destroys it (guards), when it is reachable (exposure), and when inputs change (keys). None of those show up in an apply or a passing validate.

Further reading

Drills · 10

Answer in your head, or out loud, before you reveal. Mark each one: "Again" brings it back, "Got it" counts on your desk.

1 Answer out loud

Here is a Terraform module. Five minutes: tell me what you look for, in the order you look for it, and why that order.

In short

A strong answer gives an explicit order: reproducibility first, then secrets and destroy guards, then exposure, then stable keys, then style.

What a strong answer does
  • severity ordering: States an explicit order — reproducibility (backend, locking, pinning), then leak-or-destroy risks (secrets, destroy guards, plan output), then exposure (0.0.0.0/0, public flags), then correctness under change (stable keys, data sources), then style — and says why each tier precedes the next.
  • coverage: Remote backend with locking, pinned providers and modules with a committed lock file, no secrets in code or state, prevent_destroy and deletion protection on stateful resources, network exposure, for_each on stable keys, data sources over hard-coded ids, typed and validated variables and outputs; asks for plan output.
  • communication: Tiered, each tier justified in a clause, ends with what should be automated versus what needs a human.
Why

Interviewers are listening for an order and a reason for the order, because that reveals whether you review as a mechanism or as a reader. Reproducibility comes first because every later judgement assumes the reviewed plan is the plan that will apply. Leak-or-destroy risks come before exposure because they are irreversible. Style comes last and should mostly be automated. Asking for the plan output is the tell of someone who has been burned by a -/+ line nobody read.

The common mistake

Starting with formatting, naming, or 'does it apply cleanly'. A green validate and a sandbox apply prove it runs once for you today, not that it is safe when a teammate runs it, destroys it, exposes it, or changes its inputs.

2 Quick recall

Your state is in S3 with bucket versioning on, and a teammate says that makes concurrent applies safe. It does not. What actually gives the S3 backend its lock?

In short

The answer is a DynamoDB lock table (dynamodb_table), or on Terraform 1.10+ an S3 lockfile (use_lockfile = true); versioning only lets you recover an overwrite.

Accepted

dynamodb_table · dynamodb-table · DynamoDB table

Why

Versioning keeps every overwritten state object so you can recover one; it does nothing to stop two applies from both reading serial N and both writing N+1. The lock is a separate mechanism: dynamodb_table points the backend at a table with a LockID partition key, every plan or apply writes a lock item there and fails fast with Error acquiring the state lock if one exists; Terraform 1.10+ can instead lock with a lockfile object beside the state (use_lockfile = true). You want both: the lock to prevent the overwrite, versioning to undo one.

Read the docs

3 Find what's broken

The author says the database sits in a private subnet, so this is harmless. Which line do you block on, and why is the subnet not a defence?

resource "aws_security_group" "db" {
  name        = "orders-db"
  description = "Postgres for the orders service"
  vpc_id      = data.aws_vpc.main.id

  ingress {
    description = "postgres while we debug the migration"
    from_port   = 5432
    to_port     = 5432
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"]
  }

  ingress {
    description = "postgres from the app tier"
    from_port   = 5432
    to_port     = 5432
    protocol    = "tcp"
    security_groups = [aws_security_group.app.id]
  }

  egress {
    from_port   = 0
    to_port     = 0
    protocol    = "-1"
    cidr_blocks = ["0.0.0.0/0"]
  }

  tags = { Name = "orders-db" }
}
In short

Block on line 11: port 5432 is open to 0.0.0.0/0, and a private subnet only describes routing today, not a guarantee.

What's broken
  • Line 11: Port 5432 is open to 0.0.0.0/0. A private subnet only means no route from the internet today; a misrouted peering, a bastion, a compromised pod, or a future public subnet makes this rule the whole perimeter.
Why

Security groups are the last hop of the defence, so reviewers evaluate them as if the network in front had failed. The temporary-debug rule on line 11 is the single most common finding in take-homes, and "it is in a private subnet" is the single most common defence; the answer is that routing changes silently and the rule does not. The distractors are fine: data.aws_vpc.main.id (line 4) is a data source instead of a hard-coded id, which is what you want; the security-group reference on line 19 is the correct way to admit the app tier; egress-all on line 26 is the common default — worth a question about egress filtering for a database, but not a blocker.

4 Pick the strongest answer

You are reviewing a take-home and find this:

variable "db_password" {
  type      = string
  default   = "Sup3rS3cret!"
  sensitive = true
}

The author says sensitive = true makes it fine. What do you write in the review?

  1. sensitive only redacts the value in plan and apply output. The literal is in git history and the plaintext will be written to state; remove the default, supply the value at apply time from a secrets manager, and rotate the credential because it has already leaked. Sensitivity is display metadata. Neither git nor the state file is affected by it, and a committed credential must be treated as compromised.
  2. sensitive = true encrypts the value in the state file, so the default is safe. State stores every attribute in plaintext regardless of sensitivity; protecting state is the backend's job (encryption at rest, tight IAM), not the variable's.
  3. Adding the variables file and *.tfvars to .gitignore resolves the finding. gitignore prevents future commits; the secret is already in history and in every clone, so it must be rotated and the history scrubbed.
  4. A default is only a fallback; production passes the real value through tfvars, so this is fine. The default is a real credential committed to the repository whether or not anyone uses it — and committed tfvars have exactly the same problem.
In short

sensitive = true only hides the value in output; remove the default, pass the password at apply time, and rotate it.

Why

Terraform's sensitive flag changes what the CLI prints, nothing else. The value still lives in the .tf file (and its git history) and, once used by a resource, in the state file in plaintext. The review fix has three parts: get the literal out of code (no default; pass at apply via TF_VAR_db_password or -var-file from a secret store, or let the provider generate and hold it, e.g. RDS manage_master_user_password), protect state with an encrypted and access-restricted backend, and rotate the leaked credential. Candidates who stop at "add sensitive" have not separated display from storage.

Read the docs

5 Find what's broken

This is the root of a production network stack, up for your review. Before you read a single resource, three lines would already make you request changes. Which, and what does each become?

terraform {
  required_version = ">= 1.6.0"

  backend "s3" {
    bucket = "acme-tfstate"
    key    = "prod/network/terraform.tfstate"
    region = "us-east-1"
  }

  required_providers {
    aws = {
      source = "hashicorp/aws"
    }
  }
}

provider "aws" {
  region = "us-east-1"
  default_tags {
    tags = { Env = "prod", ManagedBy = "terraform" }
  }
}

module "vpc" {
  source = "git::https://github.com/acme/tf-modules.git//vpc?ref=main"
  name   = "prod"
  cidr   = "10.0.0.0/16"
}
In short

The three faults are the backend with no locking or encryption (line 4), the provider with no version (line 12), and the module pinned to the main branch (line 25).

What's broken
  • Line 4: The S3 backend has no state locking (no dynamodb_table, or use_lockfile = true on Terraform 1.10+) and does not set encrypt = true.
  • Line 12: The provider is declared with a source but no version constraint, so every init may resolve a different major version.
  • Line 25: The module source is pinned to the main branch, so the code that runs changes whenever anyone merges.
Why

Reviewers read the terraform {} block first because everything downstream depends on it being reproducible. A remote backend without locking (line 4) is worse than it looks: S3 is durable, but two writers with the same state serial race, and the loser's resources become orphans. A provider without a version (line 12) and a module on a branch (line 25) both mean "the plan you reviewed is not the plan that will apply". The distractors are deliberate: required_version = ">= 1.6.0" is an open-ended CLI constraint many teams accept (the lock file does not cover the CLI); the state key path per stack is good practice; default_tags is a pattern reviewers like. Knowing what not to flag is part of the signal.

Read the docs

6 Find what's broken

This is the production orders database. Which lines would let one mistaken terraform apply or destroy lose the data or leak the credential, and what do you change on each?

variable "db_password" {
  type      = string
  default   = "ChangeMe123!"
  sensitive = true
}

resource "aws_db_instance" "orders" {
  identifier              = "orders-prod"
  engine                  = "postgres"
  engine_version          = "15"
  instance_class          = "db.m6g.large"
  allocated_storage       = 200
  db_name                 = "orders"
  username                = "orders_admin"
  password                = var.db_password
  multi_az                = true
  storage_encrypted       = true
  backup_retention_period = 7
  skip_final_snapshot     = true
  deletion_protection     = false
  vpc_security_group_ids  = [aws_security_group.db.id]
  db_subnet_group_name    = aws_db_subnet_group.main.name

  tags = {
    Service = "orders"
    Env     = "prod"
  }
}
In short

The three faults are the password default (line 3), skip_final_snapshot = true (line 19), and deletion_protection = false with no prevent_destroy (line 20).

What's broken
  • Line 3: A real-looking password is committed as a variable default; it is in git history and will be in state.
  • Line 19: skip_final_snapshot = true means a destroy (or a replacement) deletes the instance with no snapshot.
  • Line 20: deletion_protection = false and no lifecycle { prevent_destroy = true } block: nothing stops a destroy at either the API or the plan.
Why

Stateful resources need two independent guards: one in Terraform (prevent_destroy, which makes any plan containing a destroy of this address fail) and one at the provider or API (deletion_protection, which makes the delete call fail even from the console), plus a final snapshot so that when both are deliberately lifted there is still a recovery point. The distractors are correct as written: sensitive = true (line 4) is the right flag even though it does not fix line 3; password = var.db_password (line 15) is fine when the variable is supplied securely; multi_az (line 16) is availability, unrelated to the finding. Note also that RDS automated backups are deleted with the instance, so "we have backups" is not an answer to a missing final snapshot.

Read the docs

7 Scenario: what do you do next?

A contractor's PR adds a new Terraform root module for a customer-facing service: VPC, RDS Postgres, an ECS service, and a bastion host. About 900 lines across eight files. CI ran terraform fmt -check and terraform validate, both green. You have thirty minutes before the release train leaves and you are the only reviewer with Terraform experience.

Step 1. Where do you start?

  1. Run terraform apply against staging yourself to see what it actually creates. Applying unreviewed infrastructure code is the event review exists to prevent; plan output is the evidence you want, and you should ask for it.
  2. Read the terraform {} and provider blocks, then search the diff for literals that look like secrets, for 0.0.0.0/0, and for skip_final_snapshot/deletion_protection/prevent_destroy — before reading a single resource top to bottom. Severity first. The highest-blast-radius findings take two minutes to check mechanically, and finding them changes whether the rest of the review happens at all.
  3. Approve: fmt and validate passed, and the contractor has applied it in their sandbox. validate checks syntax and type consistency, not safety or reproducibility; a sandbox apply proves it runs, not that it is safe in production.
  4. Open the first file and comment line by line so nothing is missed. Thirty minutes of naming and formatting comments and you never reach the security group in file six. Review order should follow blast radius, not file order.

Step 2. You find four things: the bastion's security group opens port 22 to 0.0.0.0/0; the RDS instance has skip_final_snapshot = true and no deletion protection; a variable default contains what looks like a real database password; and the ECS module is sourced from a git branch. The contractor replies that the SSH rule is 'temporary while we debug'. What is your review comment?

  1. Block only on the password; the other three are judgement calls and the deadline is real. An open SSH port on the internet and a database that can be destroyed without a snapshot are not style. The deadline argues for a fast, specific list — not a shorter one.
  2. Push fixes for all four onto their branch yourself so the train can leave. Now the author has learned nothing, the review trail shows you approving your own changes, and you have taken on ownership of code you did not design.
  3. Approve with a comment asking them to tighten the SSH rule in a follow-up PR after the release. An approval is an audit record that says this was acceptable. Follow-up PRs for security fixes have a way of not happening once the release ships.
  4. Request changes with the four findings ranked by blast radius and a concrete fix for each: rotate the password and move it to Secrets Manager; add final snapshot and deletion protection plus prevent_destroy; replace the open SSH rule with SSM Session Manager or the VPN's CIDR; pin the module to a tag. Ask for terraform plan output attached to the PR. Ranked, specific, and evidence-seeking. 'Temporary' rules are how permanent holes are born, and the plan output is what lets the next reviewer see replacements and destroys.

Step 3. The fixes land and the PR merges. In the retro you are asked what would stop these four things from depending on you being the reviewer. What do you propose?

  1. Policy-as-code in CI — tfsec or checkov plus OPA/Conftest rules for the team's own conventions — that fails the pipeline on open security groups, missing destroy guards on stateful resources, unpinned providers and module sources, and secret-shaped literals; and terraform plan output posted to every PR. Turns the checklist into an enforced gate so human review can spend its time on design. Plan output on the PR makes destroys and replacements visible to non-experts.
  2. Write the review checklist on the wiki and link it from the PR template. Unenforced checklists decay; the next contractor will not read it and the next reviewer under deadline will skip it.
  3. Require two approvals on every Terraform PR. Doubles the reviewing burden without adding any mechanism; two rushed reviewers miss the same things one does.
  4. Add a pre-commit hook on developers' laptops that greps for 0.0.0.0/0. Laptop hooks are opt-in and easily bypassed, and a regex catches one of the four classes. CI is the enforcement point.
In short

Start with the terraform block, secrets, 0.0.0.0/0, and destroy guards, ask for the plan output, and end with policy-as-code in CI.

Why

The shape interviewers score in a review scenario: triage by blast radius before reading linearly; ask for evidence (plan output) rather than trusting validate or a sandbox apply; give ranked, concrete findings with fixes; refuse to trade security findings for a deadline while still being fast; and finish with a mechanism, not a reminder. "Temporary" security-group rules and "we will fix it after the release" are the two phrases a senior reviewer has learned to hear as permanent.

8 Pick the strongest answer

You pin the AWS provider with version = "~> 5.0" in required_providers and commit .terraform.lock.hcl. Tell me exactly which releases terraform init -upgrade can now pick up, and why.

  1. Any release >= 5.0 and < 6.0: the pessimistic operator lets only the rightmost component written move, so the minor floats and the major does not. With two components written, ~> 5.0 means >= 5.0, < 6.0. The lock file then records the single version actually selected, so teammates get that one until someone runs init -upgrade.
  2. Only patch releases of 5.0: the minor version is frozen. That is the meaning of a three-component constraint such as ~> 5.0.0; with two components the minor is the part allowed to move.
  3. Any release >= 5.0, including the next major version. That is what >= 5.0 means; the point of ~> is to exclude the next major, whose breaking changes are what pinning protects against.
  4. Exactly 5.0 and nothing else. An exact pin is written = 5.0 (or just 5.0); ~> is a range operator.
In short

The pessimistic ~> operator lets only the last written number grow, so the minor version can move but the major cannot.

Why

~> pins every version component except the last one written and lets that one increase. So ~> 5.0 accepts any minor release inside the same major, while ~> 5.0.0 would accept only patch releases. terraform init chooses the newest release inside the constraint and writes it to .terraform.lock.hcl; every later init reuses the locked version until init -upgrade is run. Reviewers want both halves: a ~> constraint (so an upgrade is a deliberate act) and a committed lock file (so a plan on CI and a plan on a laptop use the same provider binary).

Read the docs

9 Read the output

Nothing in this excerpt changed. Overnight the on-call replaced node-a on its own with a -target apply of an AMI bump, and it came back with a new private IP. What is this plan telling you, and what would you change in review?

# config (excerpt)
resource "aws_route53_record" "node" {
  for_each = { for i in aws_instance.node : i.private_ip => i.tags["Name"] }
  zone_id  = data.aws_route53_zone.internal.zone_id
  name     = "${each.value}.internal.example.com"
  type     = "A"
  ttl      = 60
  records  = [each.key]
}

$ terraform plan
aws_instance.node["node-a"]: Refreshing state... [id=i-0b7c3e9a1f2d4e5f6]
...

Terraform will perform the following actions:

  # aws_route53_record.node["10.0.1.14"] will be destroyed
  # (because key ["10.0.1.14"] is not in for_each map)
  - resource "aws_route53_record" "node" {
      - name    = "node-a.internal.example.com" -> null
      - records = [
          - "10.0.1.14",
        ] -> null
      - ttl     = 60 -> null
      - type    = "A" -> null
    }

  # aws_route53_record.node["10.0.1.27"] will be created
  + resource "aws_route53_record" "node" {
      + name    = "node-a.internal.example.com"
      + records = [
          + "10.0.1.27",
        ]
      + ttl     = 60
      + type    = "A"
    }

Plan: 1 to add, 0 to change, 1 to destroy.
  1. Terraform sees a missing key and a new key, not a changed record, because the for_each key is the private IP. It will destroy and create a record for the same DNS name — a resolution gap at best, a Route 53 'already exists' conflict at worst. Key on the stable instance name so an IP change becomes an in-place ~ update of records. for_each identity is the map key. An unstable key turns an attribute change into instance churn; for_each = aws_instance.node with records = [each.value.private_ip] makes the IP an attribute of a stable instance.
  2. The existing record is safe because Terraform matches Route 53 records by name and type, not by key. State maps instances by address (node["10.0.1.14"]), never by looking up attributes in the provider.
  3. The plan should have failed: for_each keys derived from resource attributes are never allowed. Terraform errors only when the keys are unknown at plan time. Here the instance already exists and its IP is known, so the plan succeeds — which is exactly why the churn is easy to miss.
  4. This is an in-place update shown as two blocks; Terraform will simply change the IP. An in-place update is a single ~ block on the same address. Two addresses with - and + mean two different instances, executed as delete and create.
In short

The for_each key is the private IP, so a new IP looks like a new record; key on the stable instance name instead.

Why

A for_each key is the instance's identity in state. When the key is derived from something that changes on its own — an IP, an ARN, a generated name — Terraform cannot know the new key is "the same thing" as the old one, so it plans a destroy of the old address and a create of the new. For a DNS record that means a gap (and, since both records share a name, a possible already exists error from Route 53 unless allow_overwrite is set). Had the instances been created in the same apply, the IPs would have been unknown and the plan would have failed with "keys derived from resource attributes that cannot be determined until apply". The review finding is the same in both cases: key on a stable, human-chosen identifier and let the volatile value be an attribute.

Read the docs

10 Find what's broken

This applies cleanly today. Two lines will do damage or fail the plan the first time the inputs change. Which, and how would you key them instead?

variable "team_users" {
  type    = list(string)
  default = ["alice", "bob", "carol"]
}

resource "aws_iam_user" "team" {
  count = length(var.team_users)
  name  = var.team_users[count.index]
}

resource "aws_instance" "worker" {
  for_each      = toset(var.worker_names)
  ami           = data.aws_ami.al2023.id
  instance_type = "m6i.large"
  subnet_id     = var.subnet_id
  tags          = { Name = each.key }
}

resource "aws_route53_record" "worker" {
  for_each = { for name, inst in aws_instance.worker : inst.private_ip => name }
  zone_id  = data.aws_route53_zone.internal.zone_id
  name     = "${each.value}.internal.example.com"
  type     = "A"
  ttl      = 60
  records  = [each.key]
}
In short

Line 7 uses count over names and line 20 keys for_each on a private IP; key both on stable, human-chosen names.

What's broken
  • Line 7: count over a list of names ties each user to a position. Removing bob shifts carol into index 1.
  • Line 20: The for_each key is the instance's private IP, a computed value that changes when the instance is replaced.
Why

Both faults are the same mistake in two forms: identity that is not chosen by a human. count identity is position, so list edits renumber instances and Terraform applies the renumbering as real changes — for IAM users that is a rename (keys and policies travel with the renamed user), for anything with a force-new argument it is a replacement. A for_each key derived from a computed attribute either churns (when known) or fails the plan (when unknown at plan time). toset(var.worker_names) on line 12 is the correct pattern, the AMI data source on line 13 is fine, and ttl is irrelevant. The staff-level follow-up is the migration: moving existing instances from team[0] to team["alice"] needs moved blocks so the fix itself does not destroy the users.

Read the docs

Next lesson Secrets and supply chain: managers, rotation, envelope encryption, signing, audit
Drill · IaC review
0:00

Loading…