Skip to content
Tech Interview Prep
Technical interview guide

Infrastructure as Code

Defining infrastructure in version-controlled configuration instead of clicking through a console: reproducible, reviewable, and diffable.

Minutes to read
4
Practice MCQs
25
Interview Q&A
25
Edition
v7
Editorial status
Reviewed

Scope: Terraform language and CLI documentation accessed 2026-08-30; OpenTofu 1.13 state encryption; current AWS CloudFormation change-set and drift behavior..

Interview Q&A

Treat each question like a live interview question: answer out loud first (structure, assumptions, tradeoffs), then open the model answer to spot gaps and rehearse a tighter follow-up.

Curated: · Written: · Reviewed:

25 questions

Q&A-1

Explain declarative IaC and where its convergence model stops.

Answer

The 90-second answer. Declarative IaC means you write the end state: three subnets, one RDS instance at 15.4, and the tool owns the how: read current state, diff against desired, build a dependency graph, apply in topological order. Terraform, CloudFormation, Pulumi and Kubernetes controllers all work this way. The convergence model stops in four places: partial application with no transaction, drift between runs, irreversible data side effects, and work that isn't a resource (data migrations, ordering against an app deploy).

Mechanism. Terraform's loop is refresh → plan → apply. Refresh calls each provider's read API and updates the state file; plan diffs that against config; apply walks the DAG, running up to -parallelism=10 operations concurrently by default. Kubernetes inverts the loop: a controller watches the API server and reconciles on every event, plus a periodic resync, so drift is corrected in seconds rather than at the next plan.

Where it stops.

No transaction. Terraform has no rollback. If resource 7 of 12 fails, the first 6 stay applied and state records them; you fix forward. CloudFormation does roll back the stack by default, but rollback can itself fail and leave DELETE_FAILED resources you clean up by hand. Kubernetes has no notion of a failed apply at all: it retries the reconcile indefinitely.

Drift. Terraform only sees out-of-band changes when you run plan or apply. Someone editing a security group in the console at 09:00 is invisible until the next run. Controllers see it immediately.

Irreversible effects. terraform destroy on an S3 bucket with objects fails unless force_destroy = true; a dropped Postgres column is gone. prevent_destroy and create_before_destroy are guardrails, not undo.

Non-resource work. Backfilling a column, reindexing, draining a node before a version bump: these are ordered against the infra change but aren't expressible as resources.

TerraformCloudFormationK8s controller
failure mid-applypartial, fix forwardstack rollback (can fail)retry forever
drift detectionon plan/applyon drift detection (manual or scheduled)continuous
undo a data changenonenonenone

Trace. 12 resources, parallelism 10. The first wave starts 10. #7 fails on an IAM eventual-consistency error. Terraform waits for the other 9 in flight, marks #7 failed, and does not start #11 and #12, which depend on it. State now holds 9 resources. Re-run after fixing: refresh finds 9, plan proposes 3.

Alternatives. Ansible is ordered tasks, not a graph: good for procedural runbooks, poor for a 500-resource graph. CDK and Pulumi generate declarative templates from real code, which helps when you need loops and conditionals but doesn't change the convergence semantics.

When not to use it. One-off data migrations, per-request dynamic infrastructure, and brownfield resources you can't import. terraform import works, but you must hand-write matching config or the next plan destroys the resource.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-23

What does idempotence mean for IaC, and what does it not mean?

Answer

Core answer

Idempotence in IaC means: apply the same configuration twice, with the same inputs and the same state, and the second apply changes nothing. The guarantee is about the plan/apply cycle, not about the API calls underneath it. In Terraform the test is mechanical: run terraform plan -detailed-exitcode; exit 0 means no changes, 2 means changes are pending, 1 means error. A second plan that exits 0 is the definition being met.

Mechanism

Terraform holds a state file mapping each resource address to a real object ID and its last-known attributes. A plan does three things: read state, call each provider's Read to refresh the object's current attributes, then diff the refreshed attributes against the configuration. Apply executes only the diff. Idempotence falls out of diffing against observed state rather than replaying the config: if the observed attributes already match, the diff is empty and nothing runs.

What it does not mean

  • Not that the provider's API calls are idempotent. CreateInstance is not idempotent; Terraform's guarantee is that it won't call it a second time when state says the instance exists.
  • Not that provisioners are idempotent. They run at create/destroy, and Terraform has no model of their side effects.

Trace:

HCL
resource "terraform_data" "audit" {          # Terraform 1.4+
  triggers_replace = [var.marker]
  provisioner "local-exec" {
    command = "echo ${var.marker} >> /tmp/audit.log"
  }
}

Apply with marker = "v1": /tmp/audit.log is v1. Plan again: no changes. Set marker = "v2": plan shows replace, apply appends, file is v1\nv2. Plan again: no changes. Terraform reports convergence while the file holds two lines: the resource graph is idempotent, the script's effect is not.

  • Not that refresh sees everything. Refresh only reads attributes the provider exposes. Anything hidden by lifecycle { ignore_changes = [...] } is invisible by construction, and attributes the provider doesn't read back (some write-only fields) can't be diffed at all.
  • Not that nondeterministic inputs are safe. value = timestamp() re-evaluates on every plan, so the plan shows an update forever. plantimestamp() (Terraform 1.5+) is stable within one plan but still differs on the next. Pass the value in as a variable instead.

By design vs by bug

Perpetual diffCauseFix
timestamp() in an argumentFunction re-evaluated each planVariable or stable derivation
desired_capacity on an ASGAutoscaler changes it out of band; Terraform fights backignore_changes = [desired_capacity]
Inline ingress blocks plus aws_security_group_ruleTwo writers for one attribute setPick one; the AWS provider documents the conflict
Provider Read returns a normalized form (JSON whitespace, list order)Provider bug or version skewUpgrade the provider; ignore_changes as a stopgap

The first three are the tool doing what it was told. The fourth is a bug: no external change, no config change, same diff every run.

Alternatives

Ansible's idempotence is per-module, not per-tool: apt and copy are idempotent, command and shell are not unless you add creates:/removes:. CloudFormation is idempotent on re-submit but has no plan: changesets are the closest, and drift detection is a separate API call. Pulumi uses the same state/diff/update model as Terraform. Kubernetes controllers are level-triggered and reconcile continuously with no plan step at all, so "idempotent" there means the reconcile loop converges, not that a run is a no-op.

Verification

Two plans with -detailed-exitcode, no config change in between. Second exits 0 → converged. Second exits 2 with the same diff → either a by-design perpetual diff or a provider bug; terraform apply -refresh-only (0.15.4+) separates real drift from a stale state file.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-2

Design the state backend for a team-managed production platform.

Answer

Assumptions first. Terraform (or OpenTofu) managing AWS, a team of 10–30 engineers, production. On GCP or Azure the backend changes but the reasoning does not.

Core answer. One S3 bucket per environment, versioning on, SSE-KMS with a customer-managed key, and S3-native state locking via use_lockfile = true (Terraform 1.10+; the DynamoDB lock table is deprecated as of 1.11). State is split by blast radius, not by team org chart: one state per environment per layer (network, data, app) so a bad apply to the app layer cannot corrupt the network state.

Why this shape: Terraform state is a JSON document mapping resource addresses to real infrastructure IDs, and it stores attribute values in plaintext, including anything you marked sensitive. So the bucket is secret-bearing production data, and versioning is the recovery mechanism: every apply writes a new object version, so a corrupted state is a list-object-versions plus copy away.

Why locking matters. Terraform does read-modify-write on state: read current, plan against it, write the whole document back. Two concurrent applies both read version N, both write version N+1, and the second clobbers the first: resources from the first apply exist in the cloud but are absent from state. The lockfile makes the second apply fail fast with Error acquiring the state lock instead of silently corrupting.

BackendLockingRecoveryPick when
S3 + native lockfileuse_lockfile=true, 1.10+S3 object versioningAWS, no extra service
S3 + DynamoDBLockID tableS3 versioningpre-1.10, or need lock TTL tooling
GCSbuilt-in lock objectobject versioningGCP
Azure blobblob leaseblob versioningAzure
Terraform Cloudbuilt-inrun historywant policy/run UI

Failure modes, detection, cost.

  • Concurrent apply clobbering: detected by the lock acquisition error; cost is orphaned resources and a manual terraform import reconciliation.
  • Truncated or partial write: detected by a plan that suddenly wants to recreate everything; restore the prior S3 version.
  • Leaked secret in state: anyone with s3:GetObject reads DB passwords. Constrain with bucket policy plus KMS key policy, and keep terraform state output out of CI logs.
  • KMS key loss: delete the key and every state version is unreadable. Enable key deletion protection and the 30-day window.

Recovery proof. Restore a nonproduction copy monthly and run terraform plan against it; an empty plan proves both the state version and the decryption key are recoverable.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-15

How do you handle concurrent IaC changes to the same environment?

Answer

What I'd say first

Serialize at the state, not at the repo. Every mainstream backend takes an exclusive lock on the state object for the duration of plan and apply, so two applies against the same state cannot interleave: the second either waits or fails fast. What actually stops a stale plan from landing is that Terraform records the state serial in the saved plan file and refuses to apply it once the serial has moved: Error: Saved plan is stale. So the rule is "re-plan after acquiring the lock, never force an approved plan through", and the tooling enforces it rather than a convention.

Mechanism

backendlocknotes
S3conditional PutItem into a DynamoDB table whose partition key is the string LockIDitem key is <bucket>/<key> (workspace prefix when workspaces are used); Terraform 1.10+ can drop the table and use S3 conditional writes via use_lockfile = true
Azure Blobblob lease on the state blob
GCSlock on the state object
ConsulKV entry held by a session

-lock-timeout defaults to 0s, so the loser fails immediately with Error acquiring the state lock and prints the lock ID, path, operation, who and created time. -lock-timeout=10m makes it retry instead. Terraform Cloud/Enterprise runs one run per workspace and queues the rest; a queued run plans when it starts, so it plans against current state. Atlantis locks per project directory and exposes atlantis unlock. GitHub Actions concurrency: {group: tf-prod, cancel-in-progress: false} queues jobs rather than cancelling them.

Worked trace (hypothetical, two CI jobs on one S3 state)

t=0.0 A acquires the lock, starts apply. t=0.0 B's conditional put fails. With the default timeout B exits; with -lock-timeout=10m B polls. t=90s A finishes, writes state serial 42→43, releases. t=91s B acquires, refreshes, plans against serial 43, applies → 44.

Counter-case: B planned at t=0 against serial 42, waited for approval, then ran terraform apply plan.tfplan at t=120s. Apply fails with Saved plan is stale because the file records serial 42. B re-plans. That is the whole answer to "don't force a stale plan".

Failure modes

  • Stale lock after a killed runner: the lock item outlives the process. Confirm the holder is gone, check the Who and Created fields in the error and the CI job status, then terraform force-unlock <ID>. Never delete the DynamoDB item by hand; you lose the audit trail and can unlock a live apply.
  • States that aren't actually independent: two states sharing a security group or an IAM role still contend at the API, not at the lock. Move the shared resource into one state with a moved block (1.1+) or terraform state mv, and reference it via terraform_remote_state or a data source.
  • Out-of-band changes: locking only covers Terraform. Console edits surface as drift on the next plan; -refresh=false hides it, so don't use it in CI.
  • -lock=false on plan is for read-only inspection only: it will happily read a state mid-write.

Splitting

Split by blast radius and change cadence: network/VPC, data stores, app config. Each gets its own state, its own lock, its own CI concurrency group. Ownership goes in CODEOWNERS so the queue is visible.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-7

How do you detect and reconcile infrastructure drift?

Answer

Core answer (first 90 seconds)

Drift is any gap between what your IaC declares and what the provider actually holds. Detect it by making the provider re-read every resource and diffing that against state: never by trusting state. In Terraform that is a refresh-only plan; in CloudFormation it is an explicit drift-detection run; in AWS Config you schedule the CloudFormation drift rule so detection is not a manual step someone forgets. Reconcile by sorting each finding into one of four buckets before touching anything: unauthorized change → revert; legitimate emergency change → codify into config; unmanaged resource → import; expected churn → suppress. The classification is the answer; the tooling only produces the list.

Detection

Terraform 1.5+:

Shell
terraform plan -refresh-only -detailed-exitcode -out=drift.tfplan
# exit 0 = no drift, 1 = error, 2 = drift present

Run it nightly in CI and again as the first step of every apply pipeline. -refresh-only re-reads the provider and updates state without proposing infrastructure changes, so it is safe against production. terraform apply -refresh-only commits the refreshed state once you have decided the real world is correct.

CloudFormation: aws cloudformation detect-stack-drift --stack-name api-prod, then aws cloudformation describe-stack-resource-drifts --stack-name api-prod --stack-resource-drift-status-filters MODIFIED DELETED. Detection is not continuous, nothing runs until invoked, so attach the AWS Config managed rule cloudformation-stack-drift-detection-check to trigger it on a schedule and surface noncompliance.

Both tools only see what the provider's read path exposes. CloudFormation drift detection covers a subset of resource properties and returns NOT_CHECKED for the rest. Terraform's refresh calls each provider's Read, so attributes under lifecycle { ignore_changes } and write-only fields never show up as drift. A clean report is not proof of convergence.

Reconciliation

findingactionwhy
Unauthorized change (console edit, rogue script)Revert: apply declared configConfig is the source of truth
Emergency change made during an incidentCodify into config, then applyReverting would undo the mitigation
Resource exists but is not in stateterraform import / CFN import, then planNext apply would otherwise duplicate or destroy it
Expected churn (ASG capacity, autoscaler)ignore_changes or drop from configThe drift is the design

Worked trace

02:14. On-call scales the api-prod ASG desired_capacity from 6 to 12 during a latency incident. 03:00. The nightly refresh-only plan reports:

~ aws_autoscaling_group.api
    desired_capacity: 12 -> 6

A plain terraform apply here scales back to 6 and re-breaks the incident. Correct move: commit desired_capacity = 12, or add ignore_changes = [desired_capacity] if the autoscaler owns it, then apply. The drift report is a question, not an instruction.

Failure modes

  • Refresh-only apply silently adopts a bad value into state; the next normal plan then "corrects" it destructively. Read the diff before apply -refresh-only.
  • Import without matching config: terraform import writes state only, so the next plan proposes destroy-and-recreate. Terraform 1.5's import blocks plus plan -generate-config-out= generate the config for you.
  • Provider Read gaps: resources with no read implementation never report drift. Track which ones and cover them with a Config rule or a smoke test.
  • CloudFormation can report IN_SYNC while a property outside the covered set has changed, and nothing re-checks until the next scheduled run.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-8

How would you bring an existing manually created resource under IaC?

Answer

The first 90 seconds

Assume Terraform against a remote backend (S3 plus a lock table, or Terraform Cloud). Two things decide the approach: does destroying this object cost data or an identity that is expensive to rebuild, and who owns its lifecycle. That picks one of three roads: import into state, recreate under Terraform, or reference it read-only with a data source.

If the answer is import: import puts the object's identity in state, not its configuration. A healthy import is followed by a plan listing every attribute you have not described yet. That diff is the actual work. Drive it to empty without applying anything that replaces the object, and never hand-edit state JSON.

Procedure (Terraform 1.5 or later, import block; terraform import on older versions)

HCL
# import.tf — declared, reviewable, shipped in the same PR as the config
import {
  to = aws_instance.web
  id = "i-0a1b2c3d4e5f60718"
}
terraform state pull > backup-$(date +%s).tfstate    # before anything writes
terraform plan -generate-config-out=generated.tf    # draft config from the real object
terraform plan -refresh-only                        # what the object actually is
terraform plan -out=tfplan -detailed-exitcode       # 0 = converged, 2 = diffs, 1 = error

The backup file restores with terraform state push. With the local backend Terraform also writes terraform.tfstate.backup; with S3 the real safety net is bucket versioning, so confirm it is enabled before the first import. Put lifecycle { prevent_destroy = true } on the resource for the duration of the adoption, and gate CI on -detailed-exitcode returning 0 so nobody applies through a plan nobody read. One caveat that bites on compute: import does not run provisioners or user_data, so an instance someone cloud-init'ed by hand becomes an object you cannot recreate from config.

Choosing the road, and when import is wrong

RoadRight whenWhat it costs
Import into stateStateful or identity-bearing: an RDS instance, an EBS volume with data, a Route53 record, a bucket holding terabytesYou inherit the manual object as-is; the first plan is large; attributes generated outside Terraform may never match config
Recreate under IaCStateless or reproducible: an instance behind an ASG, a security group, an IAM role, a launch templateDowntime or data loss, plus a cutover and a rollback path
Reference read-only (data source or remote state)Another team owns the lifecycle; you need the ID, not controlYou cannot change it, and nothing protects you from their drift
Import plus lifecycle { ignore_changes }Fields set by another controller: ASG-managed tags, an autoscaler's desired countA deliberate blind spot. Those fields can move and no plan will tell you

Import is the wrong call when the provider does not implement it: terraform import fails with "resource aws_x doesn't support import", and hand-editing state to work around that is how people corrupt a backend. terraform state push is for restoring the backup, not for edits.

Failure modes

FailureDetectionRecovery
Wrong address: the object lands at aws_instance.old, or the ID belongs to a siblingterraform state list and terraform state show <addr>; Terraform refuses an address already managed ("Resource already managed by Terraform")terraform state rm <addr> (it only disassociates, makes no API call, leaves the object alone) then import at the correct address
The first plan proposes replacementterraform plan -out=tfplan marks attributes "must be replaced" when config changes a ForceNew field such as ami, the subnet or AZ, or an RDS engineHold the apply; either make config match reality or accept the replacement inside a maintenance window
A dependent holds the ID out of bandThe plan shows unrelated resources changing; grep -r i-0a1b2c3d4e5f60718 . finds the literal ID in a security group rule or a hand-made DNS recordBring the dependent into config or change it before the apply
Two writers hit state at onceError acquiring the state lock with a lock ID from the DynamoDB tableConfirm the other run is dead, then terraform force-unlock <LOCK_ID>; never force-unlock while a CI apply is in flight
Drift the schema cannot see: a package installed by hand, a cron entryNothing. terraform plan -refresh-only stays clean because the change is outside the resource's attributesTreat Terraform's scope as the resource's API surface and put the rest in a runbook, or rebuild from config

Default rule: import when the object holds data or an identity you cannot rebuild, recreate when it does not, reference when someone else owns it.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-9

How do you refactor resource addresses without recreating infrastructure?

Answer

Assume Terraform with a remote backend, and a resource that already exists in the cloud. I'm changing its address in state, not its cloud object.

State is a map from address to instance. Each instance holds the provider's ID for the real object: i-0a1b2c3d4e5f, an ARN, whatever. Rename the block in config and the address changes, so Terraform plans a destroy at the old address and a create at the new one. A move rewrites the address key and leaves the ID alone, so no API call touches the object.

The declarative form is a moved block, Terraform 1.1+:

HCL
moved {
  from = aws_instance.web
  to   = aws_instance.app
}

The plan is the proof:

  # aws_instance.web has moved to aws_instance.app
    resource "aws_instance" "app" {
        id = "i-0a1b2c3d4e5f"
    }

Plan: 0 to add, 0 to change, 0 to destroy.

Anything other than 0/0/0 and I stop and read the plan.

Why declarative over terraform state mv: state mv works on every version and is the only option across state files, but it's an unplanned write. No diff, no PR review, and it holds the lock only for the duration of the command. A moved block lives in the config, so it's reviewed, it replays in every workspace applying that config, and the plan shows the move before anything changes.

Keep the moved block until every state holding the old address has applied. Delete it early and a workspace still on the old address plans destroy/create.

Cases that need more than one block:

  • count to for_each. Addresses change shape, so map them one at a time: moved { from = aws_instance.web[0] to = aws_instance.web["a"] }.
  • Across state files. terraform state mv -state-out=other.tfstate aws_instance.web aws_instance.app, or terraform state rm plus an import block (Terraform 1.5+).
  • Resource type change. Only if the provider implements MoveResourceState (Terraform 1.8+). Otherwise the plan shows destroy/create and you fall back to state rm + import.

Failure modes I've hit:

  • Destination already in state. Apply fails with "moved resource instance already exists": two objects claim one address. Remove the stale one first.
  • Typo'd from. A moved block whose source isn't in state is a no-op, so the plan quietly shows destroy/create. The 0/0/0 check is what catches it.
  • Provider-side replacement. A move doesn't protect you from an attribute change that forces replacement; that's a separate plan line.
  • Concurrent CI apply during manual state surgery. Take the lock, or don't do surgery.

Guardrails: lifecycle { prevent_destroy = true } on the resource so a botched refactor fails the plan instead of deleting. terraform state pull > backup.tfstate before any manual state command, restore with terraform state push.

After apply: terraform state list shows the new address, terraform state show aws_instance.app shows the same id as before, and outputs plus terraform_remote_state consumers still resolve. Anything referencing the address (outputs, other configs) moves in the same PR.

What changes the decision: a different state file or a resource never in state means moved can't reach it, so it's state mv or import. If the object genuinely should be replaced (wrong region, wrong account) don't move it, plan the replacement.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-10

Explain why rollback is usually a forward operation in IaC.

Answer

Assumptions: Terraform 1.x with an S3+DynamoDB backend, AWS provider, one environment. The same reasoning holds for CloudFormation and Pulumi; only the plan symbols differ.

The 90-second answer

Rollback in IaC is a forward operation because the tool has no inverse. Terraform is declarative and stateful: it diffs your config against a state file that records what actually exists, then calls provider APIs to close the gap. Reverting a commit changes the desired side of that diff. It does not change the current side, which the failed apply already mutated. So the next apply computes a brand-new plan from a new starting point: it is not the inverse of the failed apply.

Concretely: the failed apply created 12 of 40 resources and upgraded an RDS instance from 14.9 to 15.4. Reverting the commit plans 12 destroys, and for the engine version a replacement: -/+ in Terraform plan output, meaning destroy then create. The destroy takes the data with it; the create gives you an empty instance. AWS does not support downgrading a major engine version, so the provider either forces replacement or the API rejects the change. Either way, nothing was undone.

Why the mechanism bites

Three properties make this structural, not incidental:

  • State is the source of truth, not git. Terraform writes state as it goes, so a failed apply leaves a partially-applied state file. terraform plan after a revert diffs against that, not against the pre-apply world.
  • Providers expose create/update/delete, not undo. No API call un-deletes an S3 object or un-sends an SNS message.
  • Some changes are one-way at the platform level. Major engine version upgrades, deleted KMS keys (7–30 day waiting period, default 30, then gone), released Elastic IPs, rows written by a migration job.

When reverting a commit is fine

Revert is a legitimate rollback when the change is additive and reversible: a security group rule, a tag, an autoscaling min/max, a feature-flag default. The test is the plan after revert, if it contains only ~ in-place updates and - destroys of resources this apply created and that hold no data, revert. If it contains -/+ replacements, destroys of stateful resources, or any resource the failed apply did not create, treat it as a forward change.

Failure modes and how you detect them

  • Partial apply with no rollback. Terraform does not undo on error. Detect by reading state after the failure (terraform state list) and comparing the created count to the plan: that count is your blast radius.
  • Destroy-then-create on a stateful resource. Detect in terraform plan: -/+ on an aws_db_instance or aws_ebs_volume. This is the one that loses data.
  • Drift from out-of-band changes. Someone resized the instance in the console mid-incident. Detect with terraform plan -refresh-only before planning the revert.
  • Held or corrupted state lock. The failed run left the DynamoDB lock. Detect by a plan that fails on lock acquisition; clear with terraform force-unlock <id>.

Deciding criteria

SituationMoveWhy
Plan after revert is all ~ and safe -Revert the commitIt is genuinely the inverse
New shape reachable, data intactRoll forwardFix config, apply again; cheapest path
Stateful resource, old version not restorable in placeFail overPromote the replica; no downgrade path
Data already goneRestore from backupA data operation with its own RTO, not an IaC one

The owner named in the runbook decides between these, but the plan output is what tells them which row they are in.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-3

Walk through a production plan-and-apply pipeline.

Answer

The 90-second version. A PR triggers CI that runs terraform fmt -check, terraform validate, policy checks (OPA/Conftest or Sentinel), and a cost estimate (Infracost), then terraform plan -out=tfplan under a read-only cloud role. CI posts the diff and stores tfplan as a protected artifact. Merge to main triggers an apply job that assumes a write role via OIDC (short-lived, no static keys) and runs terraform apply tfplan: the exact bytes that were reviewed. Post-apply, smoke tests hit the deployed endpoints and a scheduled drift check re-plans against live state.

Why each stage exists.

stageidentitywhy it's there
fmt/validatenonefails in seconds before a runner spends money
planread-only rolePR code executes in CI; a fork PR must not be able to mutate prod
applywrite role, OIDC, ~1honly the merged revision, only the stored plan
post-applyread + app probeexit code 0 means the API accepted the call, not that the service works

The plan artifact must be the thing applied. A plan encodes the diff and the provider versions and data-source reads at plan time. Re-planning at apply time can produce a different diff (a new AMI ID, a changed data lookup) so what runs isn't what was approved. Terraform enforces this: if state changed since the plan, apply refuses.

$ terraform plan -out=tfplan      # state serial 41
$ terraform apply tfplan
Error: Saved plan is stale
The given plan file can no longer be applied because the state
was changed by another operation after the plan was created.

That error is the guard working. The fix is to re-plan and re-approve, not to force it.

Alternatives, and when they win.

  • Apply-on-merge without a stored plan. Simpler, one job. You approve the diff text, not the exact plan, so drift between review and apply is possible. Fine for a single-team sandbox; weak for prod.
  • Centralized platform pipeline vs per-team. Centralized gives one policy set and one audit trail, but it's a bottleneck and a single blast radius. Per-team is faster and drifts on policy. Most orgs land centralized policy, delegated workspaces.
  • Approval granularity. Approve every apply is safe and slow. Risk-based approval (replacements, IAM, data stores) is faster but depends on a classifier that can mislabel. A -/+ replacement destroys first by default: downtime, a new IP, lost data on non-persistent resources; create_before_destroy avoids the gap but briefly doubles cost and can hit quotas.

Failure modes and detection.

  • Stale plan: apply errors as above; alert on plan age vs state serial.
  • Credential scope mistake: the apply role reused by the PR job lets a fork PR mutate prod. Detect via CloudTrail AssumeRole from a PR context; the role's trust policy should pin the branch.
  • Partial apply: the provider fails mid-graph; state holds what succeeded. Detect on non-zero exit plus terraform state list; recover by fixing and re-running, since apply is idempotent.
  • State lock contention: two applies collide; DynamoDB locking or the S3 native lockfile (use_lockfile = true, Terraform 1.10+) surfaces it as a lock error.
  • Secret leakage: plan files can hold sensitive values in plaintext. Restrict artifact access and bound retention.

Post-apply validates behavior, not just exit code: hit the endpoint, check the health signal, then let the scheduled drift plan catch anything that changed outside the pipeline.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-4

How do you review a plan that replaces a stateful service?

Answer

Assumptions. The service holds authoritative state: a database, a queue, a write-back cache, a coordination store. If it's stateless this is a deploy review, not a replacement review. I assume the plan moves to a different engine or managed offering and the old service keeps serving until cutover.

The core answer. I approve a replacement plan only when it names a single writer at every instant and a bounded, measured data-loss window. Endpoint changes, quotas, IAM: that's bookkeeping. Two questions decide it: what is the authoritative copy during the overlap, and what is the worst-case RPO if cutover happens at the worst moment?

Why dual-write fails and replication works. The tempting plan is dual-write: the app writes to old and new. There's no ordering authority: two writers, two clocks, no shared transaction. A retry to one side and not the other produces divergence you can't reconcile without a merge rule. The safe pattern is single-writer plus a replication link: logical replication (Postgres logical slots), CDC (Debezium reading the WAL), or a broker fan-out. The new service consumes the stream as a shadow, you verify convergence, then you flip the writer. The replication stream is the ordering authority, so the new side is a deterministic function of the old side's log.

Trade-offs and when to reject. In-place upgrade (pg_upgrade, engine-native ALTER) is faster and keeps the endpoint, but once new-format data is written there's no rollback to the old binary. Side-by-side replacement costs double the infrastructure during overlap but gives a rollback that is just a connection-string flip. Reject the plan if it dual-writes without a reconciliation job, if it has no measured replication lag at cutover, or if the rollback path has never been exercised against production-shaped data.

Failure modes and how you see them.

failuresignalcost
Replication lag grows during cutoverpg_stat_replication.replay_lag p99 > 5scutover loses up to lag × write rate
Dual-write divergencerow-count or checksum mismatch between sidessilent data loss, found by users
Rollback unreadableold engine can't parse new rowsrollback becomes a restore, RTO in hours
Pool exhaustion at flipconnection wait p99 spikes, 5xxoutage in the window you can least afford

Arithmetic. Say the service takes 5,000 writes/s and replication lag at p99 is 2s. Cut over at the worst instant and you lose up to 10,000 writes: that's your RPO. If the business RPO is 1s, you must quiesce writes (drain, pause producers) before the flip, which turns cutover into a planned maintenance window. That number decides big-bang versus staged.

What I ask for in the plan. A cutover runbook with the exact flip command, the lag threshold that gates it, a reconciliation query for the overlap, and a rollback run in staging within the last release. Approval is a decision about the RPO, not a checklist.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-17

How should prevent-destroy controls be used?

Answer

The 60-second answer. Treat prevent-destroy as a plan-time tripwire on a short list of resources whose loss you cannot recover inside your RTO: the primary database, the Terraform state bucket, the audit-log store. It stops the accidental terraform destroy, the fat-fingered console click, the stack delete that cascades. It does not stop a determined operator, it does not survive someone editing the config, and it never restores data. So it sits on top of backups and retention, never instead of them. Keep the list short: every protected resource is one an operator has to fight during a real incident.

Match the control to the layer you're defending. These are not interchangeable: each guards one plane.

ControlLayerDefaultStopsDoesn't stop
Terraform lifecycle { prevent_destroy = true }plan timeoffterraform destroy / forced replaceconsole or CLI delete, terraform state rm
RDS DeletionProtectioncontrol-plane APIoff via CLI/API, on via consoleDeleteDBInstancedisabling the flag, then deleting
CloudFormation DeletionPolicy: Retainstack delete/updateDeletestack delete removing the resourceout-of-band delete
S3 Object Lock, compliance modeobject storageoffdelete/overwrite until retention expirescost; governance mode is bypassable with s3:BypassGovernanceRetention
Azure CanNotDelete lockARM control planeoffdelete/modify of the resourcedata-plane ops inside it (deleting a blob in the account)
Kubernetes finalizerAPI servernoneobject removal until the finalizer is clearedanyone editing the finalizer

The trap that bites most teams: replacement, not deletion. prevent_destroy fires on any plan that destroys the resource, including a forced replace. Change identifier on an RDS instance and Terraform wants to destroy-and-recreate. The plan fails:

Error: Instance cannot be destroyed
  on main.tf line 1, in resource "aws_db_instance" "primary":
   1: resource "aws_db_instance" "primary" {
Resource aws_db_instance.primary has lifecycle.prevent_destroy set, but the plan
calls for this resource to be destroyed. To avoid this error and continue with
the plan, either disable lifecycle.prevent_destroy or reduce the scope of the
plan using the -target flag.

The operator's fastest fix is to delete the lifecycle block, apply, and now the resource is unprotected with nobody watching. That is why you pair it with the API-level control: aws rds delete-db-instance --db-instance-identifier orders-primary still fails while DeletionProtection is true, independent of Terraform. Two layers, two failure modes. Note terraform state rm doesn't delete anything: it just stops Terraform tracking the resource, leaving it orphaned and unprotected.

Failure modes and how you catch them.

  • Control-plane-only protection. An Azure CanNotDelete lock on a storage account does nothing to a DeleteBlob call inside it. If the data is the asset, protect the data plane (versioning, Object Lock), not just the account.
  • Silent disablement. Someone flips DeletionProtection off in the console. Alert on CloudTrail ModifyDBInstance events that change deletion protection, and run the AWS Config rule rds-instance-deletion-protection-enabled so drift is visible before the delete.
  • Cost creep. A retained db.r6g.large Multi-AZ instance keeps billing its full hourly rate indefinitely. Retained ≠ free; track protected resources as a line item.

Break-glass. Document one procedure: disable protection, take a final snapshot, delete, re-enable on the replacement. A single reviewed change with two approvals, not an ad-hoc console session. Test it on a non-production resource quarterly so it isn't discovered during an incident.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-19

How do you evaluate the blast radius of an IaC pull request?

Answer

Assumptions: Terraform 1.5+, remote state, plan generated from a clean checkout of the PR branch after a refresh. The reasoning transfers to CloudFormation change sets and pulumi preview, where the action vocabulary differs but "replace an identity-bearing resource" is the same hazard.

Blast radius is not the resource count. It is two questions: how far does the effect propagate, and can I undo it by reverting the commit? Count answers neither: one aws_iam_policy whose document is a single "Action": "*" sweeps more than 200 tag updates.

Read the plan as actions, not resources

terraform plan -detailed-exitcode returns 2 whenever any change exists, which tells you nothing for triage. Use the structured plan:

terraform plan -out=tfplan
terraform show -json tfplan > plan.json

Every entry in resource_changes carries change.actions, and the ordering is the whole story:

actionswhat the provider doesrevert of the commit restores it?
["no-op"]nothingn/a
["update"]calls Update, keeps identityusually yes
["delete","create"]destroys first, then createsno: identity and data gone
["create","delete"]creates first (create_before_destroy)no, but no outage gap
["delete"]goneno

An update keeps the resource's ARN, endpoint and ID, so a revert re-applies the old attributes and downstream references still resolve. A replace destroys that identity. RDS ARNs are arn:aws:rds:region:account:db:identifier, so if identifier is set explicitly the ARN survives a replace; if Terraform generates it, the ARN changes and every IAM policy or DNS record holding the old value becomes a dangling reference. Detection signal: anything in the plan showing (known after apply) is a changed identity, and each consumer of it appears as its own change in the same plan.

Two more fields on the same object do the triage work. replace_paths lists the attributes that forced the replace, if engine_version, availability_zone, subnet_id, kms_key_id or ami is in there, the change is structural; if only a cosmetic attribute is, the review is about downtime, not data. action_reason says who asked: replace_because_cannot_update (provider schema says the attribute is immutable. You cannot talk your way out of it), replace_by_request (someone passed -replace=), or replace_because_tainted (state was tainted, usually by a half-failed earlier apply).

Worked trace

  # aws_db_instance.orders will be replaced, as requested
-/+ resource "aws_db_instance" "orders" {
      ~ engine_version = "14.9" -> "15.4" # forces replacement
      ~ address        = "orders.abc123.us-east-1.rds.amazonaws.com" -> (known after apply)
    }
Plan: 1 to add, 0 to change, 1 to destroy.

On apply: destroy orders. The endpoint stops answering; create the new instance; only then does any aws_route53_record with records = [aws_db_instance.orders.address] get rewritten, because its value is (known after apply) until the create finishes. Between those two events DNS answers with a hostname pointing at nothing. If a consumer holds that old address and does not show as a change in this plan (an app config, a secret, a unit in another state) the plan is telling you it exists and is out of band. That absence is the finding.

Alternatives and when this fails

Raw resource count as the gate ("over 50 resources needs a second approver") is cheap and wrong: it measures typo risk, not blast radius. Gating on replaces and deletes only is better but misses the dangerous in-place update: a security-group rule widened to 0.0.0.0/0, a route-table entry, a bucket policy. Semantic classification is stronger but has real blind spots. -refresh=false in CI hides drift. A resource created outside Terraform and never imported is invisible in the plan but live in the account. Shared resources lie: one changed route in a shared VPC route table is a single resource in the plan and takes out every workload in that VPC. And IAM policy documents come through the plan as one opaque string, not a semantic diff: you have to parse the before/after JSON yourself to see an action set widen.

Failure modes and detection

  • Renamed resource with no moved block: the plan shows a delete of the old address and a create of the new, same type and matching attributes. Destroy-and-rebuild for what should be a rename. Grep for delete/create pairs whose type matches.
  • Data-bearing replace without protection: replace_paths non-empty on aws_db_instance, aws_ebs_volume or aws_efs_file_system with deletion_protection or skip_final_snapshot unset. Recovery is a restore from the last automated backup, so RPO is the backup interval.
  • create_before_destroy on a resource with a unique-name constraint: both instances cannot coexist, the create fails, and the apply stalls half-done. The ["create","delete"] ordering in the plan is the tell.
  • prevent_destroy is a plan-time error, not a save: it rejects the plan outright, so it never hides a replace from you.

I scale process to reversibility. Reversible with no identity change: normal review, CI applies on merge. Identity change without data: a second approver who owns the downstream consumer, canaried in one region first. Data-bearing replace: named owner, maintenance window, restore tested before the window.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-16

How would you respond to a failed apply that changed some resources?

Answer

Assume Terraform 1.x with remote state and locking. A failed apply is not atomic: Terraform walks the dependency graph, calls provider CRUD operations, and writes state after each successful operation. If the provider creates a resource but returns an error, state may not contain it; if state contains it but the remote object is gone, you have drift. So the first move is not another apply.

I stop CI retries and any other writers, preserve the plan file and apply logs, and record the state serial, lineage, and provider request IDs. Then I refresh state against the real APIs and inventory actual infrastructure. I classify each resource as completed, failed, or unknown. I protect data and service before changing anything. Only then do I choose forward-fix, restore, or rollback. Manual state editing is a last resort, not a first response.

Shell
# Reconcile tracked resources with reality
terraform plan -refresh-only -out=refresh.tfplan
terraform apply refresh.tfplan

# See what state thinks exists
terraform state list
terraform show -json refresh.tfplan > refresh.json

Refresh-only works because state is a cache of last-known remote attributes. It reads the provider APIs and updates that cache for resources already tracked. It cannot import an orphan that was created but never written to state. That is why I compare terraform state list against cloud inventory, for example AWS CloudTrail for the failed API call and aws resourcegroupstaggingapi get-resources for tagged resources. The request ID from the provider error is the join key.

optionwhen it is rightcost and risk
Forward-fixFailure is transient, no data damage, refresh shows only remaining creates/updatesRe-apply can hit the same quota or permission error; if the plan includes replacement, it can destroy data
RestoreData corruption or a destructive change already appliedLoses changes after the backup; needs downtime; requires both an infrastructure snapshot and a state backup
Rollback configApp-level change, previous commit known good, resources are not replacedTerraform has no rollback command; you revert the commit and apply, which may still replace resources
Manual state editNo other path, with backup and peer reviewHigh risk of state corruption and orphaned resources

Failure modes I check with detection and cost:

  • Quota exhaustion: provider returns 429 or 403 with Throttling or LimitExceeded. Detect in the apply log and CloudTrail. Cost: partial resources and a retry storm if CI keeps firing.
  • IAM permission: 403 AccessDenied. Detect from the provider request ID and CloudTrail. Cost: apply stops after some resources are created.
  • Dependency not ready: NotFound or timeout waiting for IAM propagation. Detect from the provider error and the dependency graph. Cost: a retry is needed, but the first resources may already exist.
  • Provider bug or eventual consistency: resource created but API returns an error. Detect by diffing terraform state list against cloud inventory. Cost: orphaned resources and duplicates if you re-apply blindly.
  • Stale state lock: Error acquiring the state lock. Detect the lock ID. Cost: blocked writers. Only terraform force-unlock LOCK_ID after confirming no active apply.

Decision rule: if data is safe and the failure is transient, refresh and forward-fix. If data is at risk, stop and restore from snapshot plus state backup, then re-import or reconcile. If any operation is unknown, treat it as failed and inspect before the next apply.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-18

When should you use ignore-changes, and how do you govern it?

Answer

Assumptions. Terraform 1.x with remote state, and a resource Terraform manages where one attribute is written by something else: an autoscaler, a Kubernetes operator, a vendor agent. If nothing else writes the attribute, you do not need this at all.

When to use it. Only when a named external controller legitimately owns one attribute and you cannot move that ownership out of Terraform. The canonical case is desired_capacity on an autoscaling group: the ASG controller scales it, and Terraform would otherwise reset it on every apply. Scope it to a specific attribute, never all, and never to an attribute that carries security or availability meaning (security-group rules, IAM policy, instance type) unless a separate control enforces it.

How to govern it. Treat each entry as a contract: named owner, the exact attribute, a reason with a ticket link, an expiry/review date, and a detection path. In practice that means a comment or linked ticket on the line, PR review required for any change to the list, and an independent drift check: cloud-native drift detection, AWS Config, or a read-only data source assertion in a separate plan: that alerts when the attribute moves outside its expected range.

Mechanism. During plan, Terraform refreshes state from the remote API, then diffs config against refreshed state. An attribute in ignore_changes has its diff suppressed: Terraform keeps the value from state and plans no change. The config value is effectively frozen at creation and stops being enforced. Drift in that attribute therefore accumulates silently: refresh still records the remote value, but plan never proposes to correct it.

Worked example.

HCL
resource "aws_autoscaling_group" "app" {
  name                = "app-asg"
  min_size            = 2
  max_size            = 20
  desired_capacity    = 4
  vpc_zone_identifier = var.subnet_ids

  lifecycle {
    ignore_changes = [desired_capacity]
  }
}

Trace: the first apply creates the ASG at desired_capacity = 4. The autoscaler later scales to 12. The next terraform plan refreshes state to 12, diffs config (4) against state (12), sees desired_capacity in ignore_changes, and reports no change: Terraform does not scale back. Remove the ignore_changes line and the same plan shows desired_capacity: 12 -> 4; apply would then fight the autoscaler on every run.

Alternatives and when not to use it. If the attribute is fully owned elsewhere, delete it from the Terraform resource instead of ignoring it: cleaner, and no stale config. If you only need to skip a one-off refresh, -refresh=false or terraform import is the right tool, not a permanent ignore. ignore_changes = all (Terraform 0.13+) is almost always wrong: it hides every future attribute change, including ones you do manage.

Failure modes.

  • Silent security drift: ignoring tags or a rule attribute lets a console change that opens access persist. Detect with cloud-native drift detection or a scheduled read-only plan that asserts the attribute.
  • Stale ignore: the autoscaler is removed but the ignore stays, so the attribute is never managed again. Detect via the expiry/review date in the contract.
  • Two-controller fight: if both sides write the attribute, ignore_changes is a truce, not a fix, and the value oscillates. Detect by comparing the controller's desired value against state over time.
  • Wildcard creep: all added "temporarily" and never removed. Detect by failing CI on ignore_changes = all outside an allowlist.

Governance checklist. Named owner; narrow attribute list; reason and ticket; expiry/review date; PR review for list changes; independent drift alert; a removal plan for when the external controller goes away.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-5

How would you structure reusable modules for several teams?

Answer

First, the assumptions. I'm answering for Terraform modules consumed by roughly half a dozen teams, one cloud provider, and CI as the only path to apply. If teams apply from laptops, the drift story changes and I'd answer differently.

The structure. Modules are scoped to a capability one team owns end to end (a VPC, or a service's task definition plus ALB plus IAM role) not to a single attribute and not to the whole estate. The root module composes them and holds the provider configuration and credentials. Each module exposes typed, validated inputs, the smallest output set consumers actually need, secure defaults, an examples/ fixture, a named owner, and a version.

Why an immutable version, not a mutable tag. A git-sourced module pinned to ?ref=main means the code that ran last Tuesday and the code that runs today are different commits, with no diff in the consumer's repo. terraform plan then shows changes nobody wrote. Pin to a tag: source = "git::https://…//modules/vpc?ref=v2.3.1". Registry modules take the same idea as a version argument. Semver is the contract that makes the upgrade decision cheap: patch means no plan diff, minor means an additive optional variable, major means a renamed variable or a changed default. That's what lets a consumer decide whether to take an upgrade without reading the diff.

Why credentials live at the root. If a reusable module declares its own provider "aws" block, every consumer inherits its region and auth assumptions, and you can't run it in a second account without editing the module. Root-level providers also mean CI authenticates once, via OIDC role assumption rather than long-lived keys, and the module stays testable against a fixture root.

The competing structures, and when each wins.

structurerelease speeddivergence riskwins when
central registry, semverslow, gatedlowmany consumers, compliance review
per-team forkfasthigh: a fix lands N timesone or two teams with genuinely divergent needs
monorepo, relative pathfastestnone, but no versioning: every consumer gets HEADsingle team, or pre-1.0 interface

I'd move to the registry once a module has more than two consumers; below that the release overhead isn't worth it.

Failure modes, and how each is detected.

  • Version skew. Team A is on v1.2, team B on v1.4. A security fix in v1.4 reaches one environment only. Detect it by reading the module version recorded in state per environment, and by a scheduled terraform plan -detailed-exitcode: exit code 2 means a pending change.
  • Credential sprawl. Provider blocks inside modules duplicate secrets and widen blast radius. Detect by failing CI on any provider " block found under modules/.
  • Drift. Console edits. The same scheduled plan catches it; alert on exit code 2 rather than on plan text.
  • Breaking change. Renaming a variable fails every consumer's plan at once. Use moved blocks and deprecate across one major version instead of cutting over.

Contract tests. Each module ships a fixture root under examples/ that CI runs terraform validate and terraform plan against, plus policy checks (OPA/conftest or checkov) for encryption and required tags. terraform test (1.6+) can assert plan values directly. The matrix stays small: one fixture per supported provider major, not one per consumer.

What would change my decision. If teams need a fix shipped in hours, the registry gate is too slow: I'd go to a monorepo with relative paths, accept that there's no versioning, and reintroduce tags once the interface stabilises.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-6

Design environment isolation for development, staging, and production.

Answer

Two assumptions before I design this. First, the cloud gives me account-level isolation: AWS accounts, GCP projects, Azure subscriptions. If I'm stuck in a single account, the strongest boundary I have is IAM roles plus naming, and I'd say that out loud because it changes the whole answer. Second, infrastructure is Terraform and CI can federate identity via OIDC.

The core answer is three boundaries, ordered by how much I trust them.

One: an account per environment. This is the only boundary the cloud provider enforces for me. IAM policies, service quotas, SCPs, billing, and CloudTrail are all scoped to the account. A dev credential cannot address a prod resource ARN: it has to assume a cross-account role, and that assumption is logged. That's the blast-radius boundary: a runaway terraform apply in dev can exhaust dev's EC2 quota, not prod's.

Two: a per-environment apply identity. CI assumes a different role per environment via OIDC. The prod role's trust policy is scoped to the repo and the protected environment, not repo:*:

JSON
{
  "Version": "2012-10-17",
  "Statement": [{
    "Effect": "Allow",
    "Principal": {"Federated": "arn:aws:iam::<prod-account>:oidc-provider/token.actions.githubusercontent.com"},
    "Action": "sts:AssumeRoleWithWebIdentity",
    "Condition": {
      "StringEquals": {
        "token.actions.githubusercontent.com:aud": "sts.amazonaws.com",
        "token.actions.githubusercontent.com:sub": "repo:acme/infra:environment:production"
      }
    }
  }]
}

The sub claim is the whole security story. repo:acme/infra:environment:production means only a job running in the GitHub production environment, which I gate with required reviewers, can assume this role. Widen it to repo:acme/infra:* and any branch can apply to prod.

Three: separate state, pinned versions. Each environment has its own state backend (separate S3 bucket, or at minimum a separate key plus its own DynamoDB lock table). Modules are consumed by tag or commit SHA, never by branch. Promotion moves an immutable artifact (a container image by digest, a module by tag) through the environments. I never copy live state from staging to prod; I re-apply the same code against prod's own state.

LayerIsolatesDoes not isolate
Account per envIAM, quotas, SCPs, billing, auditBugs in shared code
Per-env OIDC roleWhich pipeline can apply whereA human with console access
Separate state + pinned tagsPlan/apply blast radiusDrift between environments

Failure modes I'd watch for:

  • Terraform workspaces as the only boundary. Workspaces share the backend and the provider credentials; terraform workspace select prod is a string. A stale TF_WORKSPACE or the wrong -var-file applies dev config against prod state. Detection: alert on any prod plan that touches more than a handful of resources.
  • Over-broad OIDC trust. Covered above; detect via CloudTrail AssumeRoleWithWebIdentity events filtered by sub claim.
  • Copying prod data into staging. Detect with data-classification tags and egress alerts.
  • Unpinned module refs. Dev and prod silently diverge. Detect with a CI check that every module source is a tag or SHA.

The cost is real: three accounts means three sets of quota increases, three billing views, and cross-account wiring for DNS and peering. That's the price of a boundary the provider enforces instead of one your team has to remember.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-14

How would you split a growing monolithic state safely?

Answer

Core answer

Split by blast radius and ownership, not by directory layout. The unit you move is a set of resources that nothing outside it references: no outputs consumed by other modules, no shared security group, no shared IAM role. Move one such slice at a time, and gate each move on an empty plan on both sides before starting the next.

Assumptions I'd state up front: Terraform 1.x, one root module, S3 backend, resources already tagged with an owning team. If those don't hold, the first job is tagging, not splitting.

Why not refactor into modules first

pathwhen it winscost
Split state now, keep one repoBlast radius is the pain: a bad plan on the VPC can destroy the databaseTwo roots to keep in sync; cross-root references become data sources or remote state reads
Module boundaries first, split laterYou don't yet know the ownership linesDelays the safety win; a single state still serializes every apply
moved blocksRenaming addresses within one stateCannot move a resource between state files: it only rewrites addresses in the same state

That last row decides a lot of designs: moved blocks are for refactoring, not for splitting. Splitting needs state surgery or re-import.

State surgery vs re-import

terraform state mv preserves the resource's recorded attributes exactly. terraform state rm + terraform import re-reads the resource from the provider API, which loses any attribute the provider doesn't return on read: some resources have write-only or computed-only fields that come back null, and the next plan shows spurious diffs. Prefer state mv; fall back to import blocks (Terraform 1.5+) only when the resource can't be moved, and always run a plan immediately after.

Worked trace

Monolith root infra/, backend key infra/terraform.tfstate, serial 412. New root dns/, backend key dns/terraform.tfstate.

# 1. inventory what you're moving
terraform state list | grep '^aws_route53'

# 2. pull both states to local files
terraform state pull > monolith.tfstate          # serial 412
(cd dns && terraform state pull > dns.tfstate)   # serial 1, new lineage

# 3. move the slice
terraform state mv -state=monolith.tfstate -state-out=dns.tfstate \
  'aws_route53_zone.main' 'aws_route53_zone.main'
terraform state mv -state=monolith.tfstate -state-out=dns.tfstate \
  'aws_route53_record.api' 'aws_route53_record.api'

# 4. push back
terraform state push monolith.tfstate
(cd dns && terraform state push dns.tfstate)

# 5. gate: both roots must plan clean
terraform plan -detailed-exitcode              # expect exit 0
(cd dns && terraform plan -detailed-exitcode)  # expect exit 0

-detailed-exitcode returns 0 for no changes, 2 for changes, 1 for error: that's the gate, not a human reading the plan.

Failure modes

  • Two roots managing one resource. If a reference was missed, both roots plan changes and the last apply wins; the resource flaps. Detect it by running plan in the old root after the move: it should show the resource gone, not modified.
  • Serial/lineage mismatch on push. terraform state push refuses when the destination serial is higher or the lineage differs. -force overrides and can silently discard a concurrent apply. Never -force without a fresh state pull first.
  • Locking. S3 backend locking used a DynamoDB table (dynamodb_table) before Terraform 1.10; 1.10+ supports native locking with use_lockfile = true. Two roots with different state keys don't collide, but if you copy a backend block and forget to change key, they do, and the second root's apply blocks or corrupts.
  • Partial import. After import, a non-empty plan means attributes weren't populated. Fix the config, don't -refresh=false past it.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-24

How do cross-state dependencies affect platform reliability?

Answer

Cross-state dependencies move a plan-time problem to an apply-time one. Inside a single state, Terraform builds the full dependency graph and refuses to plan a cycle. Across states it can't see the edges at all: terraform_remote_state is a data source that reads the last-applied state file from another backend. So reliability stops being a property of your code and becomes a property of two operational facts: is the producer's state fresh, and did the producer apply before the consumer?

Mechanism. With an S3 backend, terraform_remote_state downloads the entire state object and exposes only the declared outputs. Two consequences follow. First, the consumer's IAM policy needs s3:GetObject on the whole object, so one output leaks every attribute in that state: including secrets, which Terraform stores in plaintext (sensitive = true only redacts CLI output, not the state file). Second, the value is a snapshot from the producer's last apply, not live infrastructure.

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

resource "aws_instance" "app" {
  subnet_id = data.terraform_remote_state.network.outputs.private_subnet_id
}

If prod/network hasn't applied since the subnet was added, private_subnet_id is the old value or null; the instance lands in the wrong subnet or fails with Error: no subnet found.

Failure modes and how you see them.

FailureWhat happensDetection signal
Stale outputProducer changed, not applied; consumer plans against the old valueplan shows a diff on a value you didn't touch; output disagrees with aws ec2 describe-subnets
Cross-state cycleA needs B's output, B needs A's; Terraform can't detect itApply fails with Unsupported attribute or an empty string; a cross-repo graph shows mutual edges
Lock contentionOne lock per state; a concurrent apply blocksError acquiring the state lock with a lock ID; DynamoDB lock table pre-1.10, .tflock object after
Credential blast radiusRead on the state object = read on every attributeIAM review: consumer role has GetObject on a state it only needs one output from

Lock timeout defaults to -lock-timeout=0s, so a second apply fails immediately rather than waiting. Terraform 1.10 (Nov 2024) added native S3 locking via use_lockfile = true, removing the DynamoDB table.

Trade-off. A monolithic state gives you one graph (cycles caught at plan, one lock, one apply) but one blast radius: a bad apply can destroy resources owned by another team. Splitting buys independent blast radius and parallel applies, and charges you ordering, staleness, and a cross-team contract. Decide on change cadence and ownership: if two layers deploy in lockstep, keep them together. Split when different teams own them and they change on different schedules. Don't split a VPC from its subnets if they always change together, and don't split "to reduce blast radius" when the consumer can't function without the producer's output anyway: you've added a failure mode without removing one.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-12

How should provider and tool versions be managed?

Answer

Assume Terraform 1.x, providers from the public registry, state in a remote backend, and CI that runs init/plan/apply. The answer is two layers that do different jobs: a version constraint that states what you have actually tested, and a committed lock file that pins what gets installed. Ranges are intent; the lock file is the fact.

HCL
terraform {
  required_version = ">= 1.6.0, < 2.0.0"

  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 5.31"
    }
    random = {
      source  = "hashicorp/random"
      version = "= 3.6.0"
    }
  }
}

.terraform.lock.hcl is committed to the repo. It records the resolved version and the checksums for every provider:

HCL
provider "registry.terraform.io/hashicorp/aws" {
  version     = "5.31.0"
  constraints = "~> 5.31"
  hashes = [
    "h1:...",
    "zh:...",
  ]
}

Mechanism. terraform init resolves the constraints against the registry, picks the newest match, and writes that version plus hashes into the lock file. Every later init without -upgrade reads the lock and installs exactly that version, even after a newer one is published. So CI is reproducible without freezing the range, and moving versions is a deliberate act: terraform init -upgrade re-resolves and rewrites the lock, which shows up as a diff in review.

constraintselects
= 5.31.0only 5.31.0
~> 5.31>= 5.31.0, < 6.0.0
~> 5.31.0>= 5.31.0, < 5.32.0
>= 5.0, < 6.0any 5.x

Why downgrade is not just swapping the binary. State records the provider version and a schema_version per resource. On apply, a provider runs its state-upgrade path to migrate old state to its current schema. Upgrade aws 5.31 to 5.40 and state may be rewritten to a schema the 5.31 binary does not understand; rolling back the binary leaves you with state it cannot read, and plan or apply errors out. Recovery is restoring the state snapshot taken before the upgrade, not reverting the provider.

Pinning versus ranging. Exact pins give maximum reproducibility but no patch or security fixes without a PR, so they lag. A pessimistic range plus a committed lock gives reproducible CI and lets you pull fixes on your schedule. A wide range with no committed lock is the failure case: two engineers resolve different versions and plans diverge. Pin exact for providers whose schema changes break you or that you cannot test; range plus lock for the rest. Keep a floor on required_version because state format changes across Terraform majors.

Failure modes. Lock file gitignored: every machine resolves independently, CI and laptops drift. Detect with git status showing it untracked. -upgrade run inside CI: versions move silently. Detect a provider version change in the plan. Lock generated on darwin_arm64 but CI runs linux_amd64: checksum mismatch on init. Fix with terraform providers lock -platform=linux_amd64 -platform=darwin_arm64. A yanked provider version: init fails outright.

Upgrade workflow. One provider per PR, terraform init -upgrade, read the plan for resource-level changes, run module and policy tests, then promote through environments. Link the provider changelog in the PR so the reviewer sees what moved.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-13

How do you keep secrets out of IaC configuration and artifacts?

Answer

I'd clarify that we're talking about two things: the IaC code itself, and the artifacts it produces. Plan files, state files, CI logs, container images. My default is to never put a secret literal in code, and to treat state and plan files as sensitive data. Use references to a secret manager, and use workload identity for CI/CD. If you're on Terraform 1.10+, use ephemeral resources to keep secrets out of state entirely.

Why does state leak? Terraform state is a JSON file that stores every attribute of every resource, including sensitive ones. Marking a variable as sensitive only hides it from CLI output; it's still in state. Plan files also contain the values. So you must encrypt and restrict access to the state backend: S3 with SSE-KMS, versioning, and a bucket policy that only allows the CI role and admins. Workload identity removes long-lived credentials by having CI request a short-lived OIDC token that AWS/GCP/Azure exchanges for temporary credentials. No static keys to leak.

If you must store secrets in Git, use SOPS with age or KMS, or sealed-secrets for Kubernetes. SOPS encrypts values in place, but you still need to decrypt at apply time, and the decrypted value may end up in state unless you use ephemeral resources. Vault dynamic secrets generate short-lived credentials on demand, which is stronger but requires Vault infrastructure and application support. When not to use workload identity: if your CI provider doesn't support OIDC, or you're on-prem without a cloud provider.

Common failures: a secret committed to Git. Detect with gitleaks or trufflehog in pre-commit and CI. State file exposed: detect with CloudTrail S3 data events and AWS Config rules; cost is rotating every secret in state. Plan file shared as CI artifact: detect by scanning artifacts; mitigate by encrypting plan files and deleting after apply. Overly broad workload identity role: detect with IAM Access Analyzer; cost is unauthorized access.

Here's a Terraform 1.10+ snippet that fetches a DB password without storing it in state:

HCL
ephemeral "aws_secretsmanager_secret_version" "db" {
  secret_id = "prod/db/password"
}

resource "aws_db_instance" "main" {
  password = ephemeral.aws_secretsmanager_secret_version.db.secret_string
}

When you run terraform apply, Terraform calls Secrets Manager, gets the secret, passes it to RDS, and does not write it to state. If you're on an older version, use a regular data source and protect state as described. For CI, this GitHub Actions snippet uses OIDC:

YAML
permissions:
  id-token: write
  contents: read
steps:
  - uses: aws-actions/configure-aws-credentials@v4
    with:
      role-to-assume: arn:aws:iam::123456789012:role/terraform-ci
      aws-region: us-east-1

No AWS access keys stored in GitHub secrets.

Here's how the approaches compare:

ApproachSecret in Git?Secret in state?RotationComplexity
Literal in codeYesYesManualLow
Data source + protected stateNoYesManualMedium
Ephemeral resource (TF 1.10+)NoNoManualMedium
Vault dynamic secretsNoNoAutomaticHigh

I'd choose ephemeral resources if on TF 1.10+, otherwise data source with locked-down state. Vault if you need automatic rotation and audit. The key trade-off is between simplicity and blast radius. Protecting state is mandatory either way; ephemeral resources reduce the blast radius if state leaks. Workload identity is a must for CI.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-11

What should an IaC test strategy cover?

Answer

Assumptions first: Terraform 1.x, AWS, a CI pipeline that runs on every PR, and at least one isolated non-production account. The strategy is a layered pyramid: each layer catches what the one below cannot, and you stop adding layers when the marginal cost of the next one exceeds the risk it retires.

Layer 1: static. terraform fmt -check and terraform validate. No credentials, sub-second to roughly a second per module. Catches syntax, type, and reference errors. Runs on every commit; effectively free.

Layer 2: policy. tfsec or Checkov scan the source for security shapes: open security groups, unencrypted EBS, public buckets. OPA/Conftest enforces org rules: required tags, allowed regions, instance-size allowlists, forbidden resource shapes. Ideally against terraform plan -out JSON so it sees resolved values, not just literals. Seconds per run.

Layer 3: plan analysis. terraform plan against the real backend. This is the only cheap layer that sees the diff: which resources are destroyed or replaced, and the cost delta. A plan showing "must be replaced" on a stateful resource is the signal static tests structurally cannot give you.

Layer 4: integration. Terratest (Go) or Kitchen-Terraform deploy representative fixtures into an isolated account, assert observable behavior (curl the endpoint, read the bucket policy, connect to the database) then terraform destroy. Minutes and real dollars per run, so it runs on merge or nightly, not on every PR.

Layer 5: operational. Post-rollout smoke tests and failure injection against the deployed environment.

Provider upgrades and critical modules get regression runs against real or faithful test APIs in a sandbox account, because mocked syntax tests cannot expose quota limits, eventual consistency, or provider behavior changes.

Worked trace: bumping an RDS instance class:

  1. terraform validate: passes. The attribute is a valid string.
  2. tfsec/Checkov: no finding. Instance class is not a security shape.
  3. terraform plan: prints ~ instance_class = ... -> ... # forces replacement. The plan layer is the first to catch that this is destructive, not in-place.
  4. Integration test in the sandbox account: applies the change, confirms the new instance comes up and the app reconnects, then destroys. If the sandbox quota for db.r6g.large is exhausted, this is where it surfaces, not in the mock.
  5. Production rollout: smoke test hits the health endpoint and a read query.

The deciding criterion for how deep to go is blast radius times reversibility. A tag change in a dev account is revertible and isolated: static plus policy on the PR is the right call, and integration tests are waste. A change to shared networking, IAM, or production data is neither isolated nor cheaply revertible, so the cost of a bad apply dominates the cost of a test run and integration plus plan-diff gating is justified.

Failure modes to name: a mocked-only suite that stays green while real applies fail on quota or API deprecation; integration tests that never destroy, leaving orphans and drift; tests pointed at production state, where a stray apply destroys real data; and flaky integration tests that get disabled, so coverage silently drops to zero.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-20

Design policy-as-code controls for an IaC platform.

Answer

Assumptions: Terraform as the IaC tool, a CI gate (GitHub Actions or equivalent), OPA/Conftest as the engine, and a platform team that owns the policy repo. On Terraform Cloud/Enterprise the native option is Sentinel; the design below transfers, the syntax doesn't.

Core answer. I run policy at two points because they see different things. A static scan of the HCL (Checkov or Trivy) runs on every commit, takes seconds, and catches cheap syntactic problems. The gate that actually matters is plan-time:

terraform plan -out=tfplan
terraform show -json tfplan | conftest test -

The plan JSON carries resolved values in resource_changes[].change.after, so a rule can ask "is this RDS instance publicly accessible" instead of "does this file contain the string publicly_accessible = true".

Policies live in one repo, one directory per control, each with a Rego file, a fixture test, an owner, and a severity. Severity maps to CI behaviour: deny fails the build, warn posts a PR comment. Conftest fails on deny by default; --fail-on-warn flips warn to blocking when a control graduates.

REGO
package terraform.aws

deny contains msg if {
    some rc in input.resource_changes
    rc.type == "aws_db_instance"
    rc.change.after.publicly_accessible == true
    msg := sprintf("%s: RDS must not be publicly accessible", [rc.address])
}

The fixture test feeds it a plan JSON with one public and one private instance and asserts exactly one denial. That is what stops a policy from silently breaking when someone edits it.

Where plan-time lies to you. Plan JSON is not final state. Attributes the provider computes at apply time land under change.after_unknown, not change.after. If publicly_accessible is unknown, the rule above does not fire: that is a false negative, not a pass. For controls that must hold, either pin the value in the module or add a second check against applied state (a state scan, or a cloud-config scanner such as AWS Config or Steampipe) after apply. Plan-time is a fast gate, not a proof.

Trade-offs. OPA/Conftest is open source, spans Terraform, Kubernetes, Dockerfiles and CI config, and is unit-testable; the cost is Rego's learning curve and owning the engine. Sentinel is native to Terraform Cloud/Enterprise with policy sets and a managed runtime, but it is commercial and Terraform-only. Checkov/tfsec adopt in an afternoon with hundreds of built-in rules, but you are configuring someone else's opinions and they are weak on cross-resource logic ("this security group must not attach to that instance"). Skip policy-as-code entirely when you have one team, one repo, and low churn: CODEOWNERS plus a review checklist is cheaper and has no engine to maintain. It pays off when one invariant must hold across many teams and you need evidence that it did.

Failure modes and detection.

  • Unknown-value bypass. Detect by counting how often a deny-tier rule's key attribute appears in after_unknown across recent plans; if it is unknown more than a small fraction of the time, the control is not really enforcing.
  • Exception rot. Exceptions are data, not comments: {"control":"no-public-rds","resource":"aws_db_instance.legacy","approver":"...","expires":"2025-09-01"}. A nightly job fails if any exception is past expiry, so the list cannot grow silently.
  • False positives driving bypass. If a deny fires on legitimate work, engineers route around the gate. Track denials per week and the exception-to-resource ratio; a rising ratio means the control is wrong, not the engineers.
  • Drift from provider changes. A provider upgrade renames or adds attributes and a rule stops matching. The fixture tests catch that in the policy repo's own CI.

Rollout. A new control ships as warn for two weeks, we read the PR comments, fix the rule or the modules, then flip to deny. Every control carries an owner and a review date.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-21

How do you estimate and control IaC-driven cost changes?

Answer

The 90-second answer

IaC cost estimation is a static mapping problem, not a forecasting problem. terraform plan gives you the resource graph and attribute values; a tool like Infracost parses terraform show -json output, looks up each resource type's price from the vendor price list, multiplies by a usage assumption, and prints a monthly delta. It knows shapes and quantities, not behaviour, so it is a floor, not a prediction. I treat it as a review signal: block on large deltas with a named owner, alert on drift after deploy, and never let the estimate be the only control.

How the delta is actually derived

Three steps, each with a failure point:

  1. terraform plan -out=tfplan && terraform show -json tfplan > plan.json. The plan JSON carries every resource's type, values, and an actions array (create, update, delete, replace).
  2. Infracost maps type plus attributes to a price. aws_instance with instance_type = "m5.large" → $0.096/hr us-east-1 on-demand (illustrative list price; verify current). Times 730 hours → $70.08/mo.
  3. Usage-based line items (S3 requests, NAT gateway data processing, data transfer) have no value in the plan. Infracost substitutes a default or reads infracost-usage.yml. Unset means the delta understates.

Artefact: the replacement trap

terraform plan marks a forced replacement as -/+. For aws_db_instance, the new instance is created before the old is destroyed:

-/+ aws_db_instance.main (new resource required)
      instance_class: "db.r5.large" => "db.r5.xlarge"

During the overlap you pay for both. At $0.24/hr vs $0.48/hr (illustrative), a 30-minute overlap adds ~$0.12: trivial. The real cost is the snapshot and the cutover risk, not the double-billing. Estimate tools show the steady-state delta and miss the transition.

Trade-offs: where to put the gate

ControlFeedback speedCatchesMisses
Infracost in CI (block)minutes, pre-mergeshape changes, SKU swapsusage, orphans, drift
AWS Budgets + SNSdailyaggregate overspendwhich change caused it
Cost Anomaly Detection~daily, MLunexpected spikesslow ramps
Cost Explorer grouped by tagnext dayactual vs estimatenothing pre-merge

Deciding criterion: block in CI only when the delta is both large and attributable to a known resource. If usage is unknown, an advisory comment plus a budget alert catches the same thing without false-positive friction.

Failure modes and detection

  • Unsupported resources → silent $0. Infracost prints an unsupported-resource count; fail the job when that count is nonzero for types you care about.
  • Orphans: removing a resource from config without terraform destroy, or terraform state rm, leaves it billing. Detect with AWS Config or Cost Explorer filtered to untagged resources.
  • Tag drift: console-created resources miss default_tags. Enforce with an Organizations tag policy or SCP requiring owner.
  • Estimate-vs-actual gap: reconcile monthly. infracost breakdown against applied state vs Cost Explorer grouped by tag. A persistent 30% gap means your usage file is wrong.

Emergency changes: retrospective review is fine, but the tag and the budget alert still apply. Attribution is not optional.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-25

How would you secure and operate encrypted state and plan files?

Answer

Threat model first, then the answer. Two distinct adversaries matter here. One is someone who gets the storage (a leaked S3 object, a stolen laptop, a misconfigured backup bucket) and should learn nothing. The other is an authorized runner that legitimately decrypts state during a plan or apply; you cannot stop it reading secrets, so you bound what it can reach and log it. Terraform state and plan files both hold plaintext secrets (RDS passwords, private keys, generated tokens), so both need the same treatment. My default: Terraform's native encryption block (1.7+) with a KMS key provider, enforced = true, one key per environment, and no reliance on backend-side encryption alone.

Mechanism: envelope encryption. Terraform generates a per-state data key, encrypts the state with AES-GCM, and wraps that data key with the KMS key. The backend only ever stores ciphertext; the KMS key never leaves KMS. That is the difference from S3 SSE-KMS, where the object is encrypted at rest but anyone with s3:GetObject plus kms:Decrypt gets plaintext, and the backend operator sees it too.

HCL
terraform {
  encryption {
    key_provider "aws_kms" "env" {
      kms_key_id = "arn:aws:kms:us-east-1:111122223333:key/abcd-..."
      key_spec   = "AES_256"
    }
    method "aes_gcm" "env" {
      keys = key_provider.aws_kms.env
    }
    state { enforced = true
            method   = method.aes_gcm.env }
    plan  { enforced = true
            method   = method.aes_gcm.env }
  }
}

enforced = true makes Terraform refuse to read or write unencrypted state, which is what stops a half-migrated workspace from silently staying plaintext.

Trade-offs, and the criterion that decides them.

OptionProtects againstDeciding criterion
S3 SSE-KMS onlydisk/object theftbackend and any kms:Decrypt holder still see plaintext
Terraform-native + KMSbackend, storage, backupsneeds 1.7+ and a KMS key per env
Terraform-native + PBKDF2 passphraseno KMS dependencythe passphrase becomes the new secret to distribute

Pick KMS when you already run cloud IAM and want key access audited and revocable; pick PBKDF2 only where no KMS exists, and accept that passphrase rotation means re-encrypting everything.

Rotation is cheap because of the envelope. Methods accept a list of keys: the first encrypts, all are tried on decrypt. To rotate, prepend the new KMS key, run any state write (a no-op terraform apply or terraform state pull/push cycle) to re-wrap the data key, then drop the old key. The 50 MB state is re-encrypted locally at AES-GCM speeds (sub-second); KMS sees a handful of Encrypt/Decrypt calls, not per-byte traffic: at $0.03 per 10,000 requests, rotation costs fractions of a cent.

Failure modes and how you catch them.

  • Key loss. A KMS key scheduled for deletion (7–30 day window) makes state unreadable. Detection: a scheduled restore drill that decrypts a real state file fails loudly.
  • Stale runner credentials. A key-policy change drops kms:Decrypt from the CI role; plans fail with AccessDenied on the key, not on the bucket: that distinction is the tell.
  • Partial migration. Some workspaces never got the encryption block. Detection: terraform state pull on each workspace and grep for plaintext markers, or assert enforced in a policy check.
  • Plan files as CI artifacts. terraform plan -out=tfplan uploaded to a build artifact store leaks secrets unless plan encryption is configured; treat the artifact as secret-bearing.

What changes the decision: if you cannot guarantee KMS availability during an incident, keep a documented break-glass path (a second key provider in the method list) rather than a plaintext fallback. A fallback that decrypts is the failure you were defending against.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-22

How would you adopt IaC in an organization with heavy console usage?

Answer

Assumptions I'd state up front: a few hundred to low-thousands of resources, one cloud (say AWS), Terraform as the tool, no existing state, and operators who currently fix incidents in the console. If any of those is wrong the plan changes: I'll say where.

The core answer: import before you restrict. Do not freeze console writes first. Terraform's plan is a diff between state and config. A resource that exists in the cloud but not in state is invisible to Terraform, so a plan written against it proposes to create it: apply makes a second copy. So the order is: write config, import the real resource IDs into state, get terraform plan to come back empty, and only then restrict console writes. Once plan is empty, config is a faithful description of reality, and any console change surfaces as drift instead of being silently reverted or duplicated.

Mechanism, concretely. Terraform 1.5+ lets you import declaratively:

HCL
import {
  to = aws_security_group.web
  id = "sg-0a1b2c3d4e5f67890"
}

terraform plan -generate-config-out=generated.tf writes matching HCL for you. Treat that output as a starting point, not final: it includes computed attributes you should strip. Then terraform apply imports. To reconcile drift without touching infrastructure, terraform plan -refresh-only shows what changed outside Terraform and terraform apply -refresh-only accepts reality into state. terraform plan -detailed-exitcode returns 0 (no changes), 2 (changes), 1 (error): wire that into CI so drift raises an alert rather than waiting for the next human apply.

Trade-offs and when this is wrong. Phased import by service or account is right when blast radius is high or ownership is unknown; big-bang import in one week is fine under roughly 200 resources with clear owners. Restrict-first is correct only when state already matches reality: otherwise you block the operators you need to fix drift. Importing everything into one state file is the common mistake: a 3,000-resource state makes every plan slow and one bad apply can touch unrelated services. Split by service, account, and lifecycle.

Failure modes, detection, cost.

  • Console edit reverted by the next apply. Someone widens a security group during an incident; the next apply narrows it back and causes an outage. Detect with a refresh-only plan in CI; alert on any drift.
  • Duplicate resource from config-without-import. Plan shows create, apply makes a second load balancer. Detect by diffing terraform state list against a cloud inventory.
  • Concurrent applies without locking. Two CI runs race and corrupt state. Use an S3 backend with use_lockfile = true (Terraform 1.10+, where DynamoDB locking is deprecated) or DynamoDB locking on older versions. Detect via lock-acquisition errors.
  • Unaudited emergency console route. The change never enters state and drift compounds. Detect by comparing CloudTrail write events against state.

Metrics with targets. Managed coverage = managed resources / total (aim >90% for stateless, lower for stateful); drift age = time since the last refresh-only plan showed changes (alert past 24h); failed-change rate; lead time from PR to apply.

wavescopeexit criterion
0one low-risk serviceempty plan, CI drift check green
1stateless servicescoverage >90%, console writes denied
2stateful (DB, queues)restore exercise passes
3remaining accountsemergency route audited, drift age <24h

Each wave's exit criterion is the gate to the next; a wave that never reaches an empty plan is a signal the config is wrong, not that the team should push harder.

Curated: · Written: · Reviewed:

Difficulty: Hard