Terraform in operation: remote state, drift, import, moved, workspaces, blast radius

Plan review is the control. Import what exists, keep workspaces separate, and make the destroy lines the thing you read first.

Read the briefing
About 10 min to read 8 drills

What to remember

  1. Read the plan bottom-up: what gets destroyed? Replacements and destroys are where the outage lives, not in the adds.
  2. Import before you re-declare. Declaring an existing resource without importing creates a duplicate or a conflict.
  3. Separate state per environment. One state file for prod and staging is one typo away from a very bad afternoon.
  4. terraform apply in CI, with a reviewed plan artefact. The plan a human approved must be the plan that runs.
  5. Drift is normal; unexplained drift is a finding. Detect it on a schedule and reconcile deliberately.

The big picture

Terraform in production is less about writing HCL than about operating the state file: keeping one locked copy of the truth, reading a plan well enough to know what an apply will destroy, and changing state on purpose (import, moved) without touching infrastructure. Interviewers probe this layer because it is where the real outages come from: a lost state write, a drift revert applied blind, a rename that planned a replacement, or a password that quietly landed in a bucket half the company could read.

The mental model

Picture three documents that must agree: the configuration (what you want), the state (what Terraform believes exists, keyed by resource address), and reality (what the cloud API says). plan refreshes state from reality, then diffs configuration against the refreshed state, and every symbol in the output is a statement about one of those three drifting from the others. Operations is the discipline of keeping the three aligned deliberately: locks so only one writer edits state at a time, import and moved to fix the mapping without recreating anything, and boundaries small enough that one wrong plan cannot take everything with it.

In depth

State is a shared document; the lock is what makes it one

A remote backend stores the state object (a JSON document with a serial that increments on every write and a lineage that identifies the history it belongs to) somewhere every operator and CI runner can reach, and takes a lock for the duration of any operation that might write it. With the S3 backend the lock is a DynamoDB item keyed by LockID (or, on Terraform 1.10+, an S3 lockfile object enabled with use_lockfile = true); the lock record carries who took it, when, and which operation.

Without a lock, two applies that start seconds apart both read serial N, both act on the cloud, and both write serial N+1. The second write wins and the first apply's resources exist in AWS but not in state. Nothing errors. The next plan shows them as + creates, and the apply either fails on name conflicts or, worse, creates duplicates. S3 versioning does not prevent this; it only lets you recover the overwritten document afterwards, which is why you turn it on anyway. The DynamoDB table also holds a digest of the state so the backend can detect a document that was replaced underneath it; without the table there is no check at all.

What to check when a run fails with Error acquiring the state lock: the lock info names the holder (Who: ci@runner-7), the operation, and the time. Confirm that process is really dead (the CI job is gone, the laptop is not mid-apply), then terraform force-unlock <ID>. Never -lock=false in a pipeline and never delete the lock item by hand: the ID check is the safety. After any interrupted apply, compare the state serial with the run log (terraform state pull | jq .serial), because a process killed while waiting for a resource to become ready can leave an object created but unrecorded.

Reading a plan: symbols, drift, blast radius

Read the symbols before the attributes. + create, - destroy, ~ update in place, -/+ destroy then create (the default replacement order), +/- create then destroy (when create_before_destroy is set), <= a data source that will be read during apply because its inputs are not yet known. Next to a ~ attribute inside a -/+ block, # forces replacement names the argument the provider cannot change on the existing object. (known after apply) marks values that do not exist yet, which is why dependents of a replaced object also show ~. The summary line counts a replacement as one add and one destroy.

Drift is reality differing from state. plan refreshes first, so drift shows in two places: a Note: Objects have changed outside of Terraform block describing what refresh found (an added security-group rule, a deleted role), and then the actions block, which already incorporates it. Configuration is the source of truth, so an out-of-band change appears as a ~ that reverts it, a deleted object as a + that recreates it, and a manual change to a force-new attribute as -/+. Drift does not block an apply; it is folded into it. terraform apply -refresh-only is the tool for the opposite decision, accepting reality into state without changing anything, and it is the wrong tool when the console change should become code.

Blast radius is read from the plan, not from the diff of the HCL. The habit: any - or -/+ on a stateful resource (database, bucket, volume, DNS zone) stops the review until someone explains it; any ~ you did not cause is drift to investigate, not noise to apply. -target and -replace are scalpels for incidents, never pipeline flags, and terraform show -json plan.out is how a CI policy reads the same symbols a human does.

import and moved: editing state without touching infrastructure

import binds an existing object to a resource address: terraform import aws_nat_gateway.main nat-0b6d... or, in modern Terraform, an import { to = aws_nat_gateway.main id = "nat-0b6d..." } block that participates in plan and can even write starter configuration with -generate-config-out. Import never modifies the object; it writes its identity and current attributes into state. The work is what follows: run plan, read every ~ it proposes, and change the configuration until the plan is a no-op. A plan that still wants to "fix" ten attributes after an import means your configuration does not yet describe the real thing, and applying it would change production to match your guess.

moved fixes the other kind of mapping problem: the object is right, the address changed. Renaming a resource, moving it into a module, or converting count to for_each all give the object a new address, and without help Terraform plans a destroy at the old address and a create at the new one. A moved { from = aws_db_instance.orders to = module.orders_db.aws_db_instance.this } block tells the planner they are the same object. The semantics matter: from must no longer exist in configuration; a from that matches nothing in state is silently a no-op (so a typo in the old address gives you exactly the destroy you were trying to avoid); blocks are idempotent and can stay in the code as history. moved works within one configuration. Moving an object to a different root module means terraform state mv across pulled state files, or a removed block (stop managing without destroying) in the source plus an import in the destination.

Verification is the same in every case: a plan that shows zero changes on every side afterwards. Merge the refactor only with that plan attached.

Workspaces versus one root module per environment

CLI workspaces give one root module several state files under one backend: terraform workspace new staging creates a state object at env:/staging/<key> in S3, and terraform.workspace lets the configuration branch on the name. Everything else is shared: the same code at the same commit, the same .terraform.lock.hcl and provider versions, the same backend bucket and lock table, and, unless you plumb it through variables, the same credentials. That is the failure mode. A change merged to the module reaches production's next plan whether or not staging has proven it; a terraform destroy run in the wrong workspace executes with whatever permissions the shared role has; a provider bug found in dev blocks prod at the same moment. terraform workspace show is the only thing separating the environments.

Separate root modules per environment (envs/prod, envs/staging, each a few dozen lines calling a shared, versioned module) cost duplication but buy real isolation: their own backend keys, their own roles or accounts, their own provider lock files, and independent module version bumps so prod can lag a release while staging proves it. The shared module absorbs the duplication; the roots hold only what differs. Workspaces remain reasonable for ephemeral copies of the same thing (a preview stack per pull request) where identical code and identical credentials are the point.

Note the naming trap: HCP Terraform and Terraform Enterprise "workspaces" are a different object with their own variables, credentials, and run history, closer to a per-environment root than to a CLI workspace. Interviewers sometimes use the word loosely; ask which one they mean before answering.

Secrets and the state file

State stores every attribute of every managed and read object in plaintext JSON. A random_password result, an RDS master password you passed in, a generated private key, the payload of an aws_secretsmanager_secret_version data source: all of it is in the state document, and sensitive = true changes only what the CLI prints. The state bucket is therefore a secret store whether you meant it to be or not, and outputs make it an API: anything exposed as a root output is readable by every terraform_remote_state consumer, and reading the bucket directly gives everything else.

The operating rules follow from that. Encrypt the backend (encrypt = true plus a KMS key) and treat read access to the bucket and the lock table as access to every secret in it: CI roles and a break-glass group, not the whole engineering organisation. Keep secret material out of Terraform where the provider allows it: manage_master_user_password = true on aws_db_instance writes the credential straight to Secrets Manager and Terraform only ever sees the ARN; reference secrets by ARN or name and let the consuming service fetch them with its own IAM permission. Never publish a secret as an output for another stack to read; publish the ARN. Terraform 1.10+ adds ephemeral values (and 1.11+ write-only arguments) so some secrets never enter state at all, which is the direction to move as providers support it.

If a state file with secrets in it has been exposed (a public bucket, a copy on a laptop, a pasted terraform state pull), rotate; the leak has already happened, and encryption at rest did not cover the person who had s3:GetObject.

Blast radius, guards, and what a reviewer checks

Two Terraform operations delete data: terraform destroy and any plan containing - or -/+ on a data-bearing resource. Three independent guards exist and a serious configuration uses all of them. lifecycle { prevent_destroy = true } fails any plan that would destroy the resource, at plan time, from configuration. Provider-level protection (deletion_protection = true on RDS, force_destroy = false on S3) makes the API refuse the delete regardless of who asks. A final snapshot (skip_final_snapshot = false with a final_snapshot_identifier) leaves a recovery point when both guards are deliberately lifted. The fourth guard is process: plan output posted on every pull request and a CI policy (OPA, Sentinel, or a script over terraform show -json) that fails on planned destroys of protected types unless the PR carries an explicit label.

State boundaries are the guard nobody writes down. One state per blast-radius domain (network, identity, cluster, each stateful service) and per change cadence keeps a stuck lock, a provider upgrade, or a bad plan from blocking or endangering everything at once; cross-stack references go through data sources or a small set of outputs, and dependencies point one way. A 25-minute apply that touches hundreds of resources on every PR is a boundary problem, not a performance problem.

The take-home review checklist, in the order a reviewer reads: a remote backend with locking and encryption; providers and module sources pinned with a committed .terraform.lock.hcl; data sources instead of pasted ids and ARNs; typed variables with validation blocks and descriptions; consistent naming and tags (default_tags); outputs that a consumer actually needs; no secrets in code, tfvars, or outputs. Then ask for the plan, because the plan is where the reviewer sees what the code will actually do.

Myths and facts

Myth: S3 versioning on the state bucket is state locking.

Fact: Versioning lets you recover an overwritten state object; locking prevents the overwrite. You need both: DynamoDB or an S3 lockfile for the lock, versioning for the undo.

Myth: sensitive = true keeps the value out of the state file.

Fact: It only redacts CLI output. Every attribute, sensitive or not, is stored in plaintext in state; protection is the backend's encryption and the IAM on who can read it.

Myth: terraform import updates the real resource to match my configuration.

Fact: Import only writes the object's identity and attributes into state. The configuration then has to be edited until plan is a no-op, or the next apply changes the real thing.

Myth: Workspaces give each environment its own backend, credentials, and provider versions.

Fact: They share code, backend, lock file, and credentials; only the state key differs. Separate root modules are how you get separate permissions and independent version bumps.

Myth: -/+ is just an update with extra steps.

Fact: It is destroy, then create. For a database or a bucket that is data loss followed by a new empty object; the # forces replacement marker tells you which argument caused it.

Myth: If objects changed outside Terraform, plan refuses to run until I refresh.

Fact: Refresh happens inside plan. Drift is reported in a note and folded into the proposed actions; -refresh-only is for accepting drift into state, not a prerequisite.

Myth: A moved block with the wrong from address will fail loudly.

Fact: A from that matches nothing in state is a legal no-op, so a typo produces exactly the destroy and create you were trying to prevent. Verify with a plan that shows zero changes.

How pros do it

  • Lock every backend and keep versioning on the state bucket; force-unlock only after confirming the holder is dead, and never run with -lock=false in CI.
  • Post the plan on every pull request and gate on it: any - or -/+ touching a protected resource type fails CI unless the PR is explicitly labelled to allow it.
  • After every import, moved block, or refactor, require a no-op plan before merging; a plan that still shows changes means the mapping or the configuration is wrong.
  • One root module per environment and per blast-radius domain, each with its own backend key and its own role or account, calling shared modules pinned to a tag.
  • Keep secrets out of state where the provider allows it (manage_master_user_password, references by ARN); never expose a secret as an output; encrypt the backend and restrict reads to CI and break-glass.
  • Pin every floating input that can change a plan on its own (AMI ids, module refs, provider versions) and promote changes by pull request instead of by data-source drift.
  • Codify emergency console changes within a day and run a scheduled drift plan; a drift you first discover during an incident is a drift you will apply blind.

Questions people ask

Should I use workspaces for dev, staging, and prod?

Say no for long-lived environments and give the reason as what workspaces share: a CLI workspace is only a separate state key, so code, provider versions, backend, and credentials are shared and a mistake or an upgrade in one is a mistake in all. Recommend one root module per environment, with its own backend key and role, calling a shared versioned module, and keep workspaces for ephemeral copies such as per-PR preview stacks. Ask whether they mean CLI or HCP Terraform workspaces, which do carry their own variables and credentials.

My plan shows changes I never made. Is my state corrupted?

Name it as drift before anyone says 'corruption': someone changed the resource outside Terraform and the plan proposes to put it back the way configuration says. Then give the procedure: read the 'changed outside of Terraform' note, decide per change whether the console edit should become code, and only then apply. Add what corruption actually looks like, so they know you have seen it: whole resources missing, or a serial that went backwards.

How do you structure state for many teams, and how small should one state be?

Give the rule, then the trigger. Small enough that one lock, one provider upgrade, or one bad plan cannot block or endanger unrelated things: one state per environment per domain (network, identity, cluster, each stateful service), each with its own backend key and role, with dependencies pointing one way. The trigger to split is every PR's plan touching hundreds of resources. Name the cost: more roots means cross-stack plumbing to maintain.

The state is locked but nobody is running Terraform. Can I just force-unlock it?

Yes, with a condition, and say the condition first: the holder named in the lock info is confirmed dead (the CI job finished or was killed, the laptop is not mid-apply). Use terraform force-unlock <ID> rather than deleting the lock item, and never -lock=false. Then say what you check next: whether the interrupted run wrote state or left an object created but unrecorded.

How do I rename a resource or move it into a module without destroying it?

A moved block from the old address to the new one (or terraform state mv), and the proof: a plan that shows zero changes and a has moved to line. Volunteer the trap: a from that matches nothing in state is silently a no-op, so copy the old address from terraform state list. If they push on cross-root moves, say moved does not cross root modules; that takes state mv across pulled state files, or a removed block plus an import block in the destination.

The state bucket is encrypted, so is it fine that the database password is in state?

No, and give the threat model in one sentence: encryption at rest protects against a stolen disk, not against anyone with s3:GetObject on the bucket, which is exactly who reads state. Say that state readers are secret readers, then offer the by-construction fix: let RDS manage the password so only an ARN lands in state, and never expose a secret as an output.

I imported a resource and the plan wants to change a dozen attributes. Did the import fail?

Say the import worked and the configuration does not yet describe the real object: import writes identity and attributes into state and touches nothing, so each proposed ~ is a gap between the code and reality. Add the attribute or accept the change deliberately, and stop when plan is a no-op; applying before that would change production to match your guess.

Further reading

Drills · 8

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

1 Pick the strongest answer

Two engineers run terraform apply on the network root about 4 seconds apart. State is in S3 with versioning on, but the backend has no dynamodb_table and no use_lockfile. Both applies print Apply complete!. What has actually happened to state, and what would a lock have changed?

  1. S3 versioning reconciles the two writes, so state is complete and nothing is lost. Versioning stores both documents as separate versions; the current version is simply the last write. It lets you retrieve the overwritten state afterwards, which is a recovery path, not a prevention.
  2. The second apply is rejected because Terraform notices the state serial changed underneath it. The S3 backend's consistency check (the state digest) lives in the DynamoDB lock table; without locking configured there is nothing to compare against and the write goes through.
  3. Both runs read the same state serial, both created the missing resources, and the second state write overwrote the first: some real resources now exist with no entry in state. The next plan proposes to create them again (+) and the apply fails on name conflicts or creates duplicates; recovery is terraform import, and a lock would have made the second run fail fast with Error acquiring the state lock. Without a lock there is no serialisation and no serial check, so the last writer wins and the loser's objects become invisible to Terraform.
  4. Nothing goes wrong: apply is idempotent, so two applies converge on the same result. Idempotence holds for sequential applies against a consistent state; two applies working from the same snapshot both create the missing objects and then race on the write.
In short

Without a lock the second state write overwrote the first, so some real resources are now missing from state and the next plan wants to create them again.

Why

State is a document with a serial; every apply reads it, acts, and writes it back. A lock is what turns "reads and writes" into "one writer at a time". Without it, two applies that start from serial N both believe the same resources are missing, both create them (the cloud may reject duplicates or may not, depending on whether names must be unique), and both write serial N+1; the second write replaces the first, and the first run's objects are orphaned from Terraform's point of view. The S3 backend stores a digest of the state in the DynamoDB table precisely so it can detect a replaced document, which is why the fix is dynamodb_table (or use_lockfile = true on Terraform 1.10+), not a bigger bucket. Versioning stays on so the overwritten state can be pulled back when you need to reconstruct what happened.

The common mistake

Saying S3 versioning makes concurrent applies safe. Versioning keeps the overwritten document so you can get it back; only a lock stops the overwrite.

Read the docs

2 Pick the strongest answer

A platform team runs three environments of the orders stack, dev through prod, as CLI workspaces of one root module: one S3 backend, one .terraform.lock.hcl, one CI role. Workspaces or separate roots: what is actually true about what this setup shares and what it separates?

  1. Each workspace has its own state object (S3 stores non-default workspaces under env:/<name>/<key>), but every environment shares the same code at the same commit, the same provider versions, the same backend and lock table, and the same credentials. A merged change reaches prod's next plan regardless of staging results, and a terraform destroy in the wrong workspace runs with prod-capable permissions. Separate root modules per environment calling a shared versioned module give independent blast radius, permissions, and version pinning at the cost of some duplication. Workspaces separate state only; isolating credentials, versions, and rollout order requires separate roots.
  2. Workspaces isolate environments fully: each has its own backend configuration, credentials, and provider lock file. A root module has exactly one backend block and one lock file; workspaces vary only the state key beneath it.
  3. The setup is fine once production-only resources carry count = terraform.workspace == "prod" ? 1 : 0. Conditionals on the workspace name make the environments diverge inside one code path and do nothing about shared credentials or shared upgrades; they are the signal that the environments wanted separate roots.
  4. All workspaces write to one state file, with the workspace name prefixed onto every resource address. Each workspace is a separate state document; resource addresses are identical across workspaces, which is exactly why terraform.workspace is needed to vary names.
In short

Workspaces separate only the state file; code, provider versions, backend, and credentials are shared, so separate root modules give real isolation.

Why

A CLI workspace is a state key, nothing more. That is useful when you want N copies of exactly the same thing with the same credentials (a preview stack per pull request) and harmful when the copies are supposed to differ in who may touch them and when they receive changes. Long-lived environments want three independent knobs: which code version applies (so prod can lag staging by a release), which credentials apply (so a dev laptop cannot reach prod), and which state and lock they use (so a stuck lock or a provider upgrade in one does not block the other). Per-environment root modules give all three; the shared module keeps each root to a page of inputs. When an interviewer says "workspaces", ask whether they mean CLI workspaces or HCP Terraform workspaces, which do carry their own variables and credentials.

The common mistake

Treating a CLI workspace as an environment boundary because it has its own state file. It has its own state key and nothing else; terraform workspace show is the only thing between a dev destroy and prod. Ask whether they mean CLI or HCP Terraform workspaces before answering.

Read the docs

3 Read the output

The only change in this pull request is a new filter on data.aws_ami.al2023. Read me the plan: what has happened outside Terraform, what will apply do, and which part causes downtime?

$ terraform plan
data.aws_ami.al2023: Reading...
aws_iam_role.deploy: Refreshing state... [id=deploy]
aws_security_group.web: Refreshing state... [id=sg-0f3a9c2b1d4e5f678]
aws_instance.web: Refreshing state... [id=i-0a1b2c3d4e5f60718]
data.aws_ami.al2023: Read complete after 1s [id=ami-0e1d30f2c40c4c701]

Note: Objects have changed outside of Terraform

Terraform detected the following changes made outside of Terraform since the
last "terraform apply" which may have affected this plan:

  # aws_iam_role.deploy has been deleted
  - resource "aws_iam_role" "deploy" {
      - arn  = "arn:aws:iam::123456789012:role/deploy" -> null
      - name = "deploy" -> null
        # (6 unchanged attributes hidden)
    }

  # aws_security_group.web has changed
  ~ resource "aws_security_group" "web" {
        id      = "sg-0f3a9c2b1d4e5f678"
      ~ ingress = [
          + {
              + cidr_blocks = ["0.0.0.0/0"]
              + from_port   = 22
              + protocol    = "tcp"
              + to_port     = 22
                # (5 unchanged attributes hidden)
            },
            # (1 unchanged element hidden)
        ]
        # (7 unchanged attributes hidden)
    }

Terraform will perform the following actions:

  # aws_iam_role.deploy will be created
  + resource "aws_iam_role" "deploy" {
      + arn                = (known after apply)
      + assume_role_policy = jsonencode({ Statement = [ ... ], Version = "2012-10-17" })
      + name               = "deploy"
    }

  # aws_instance.web must be replaced
-/+ resource "aws_instance" "web" {
      ~ ami           = "ami-0c55b159cbfafe1f0" -> "ami-0e1d30f2c40c4c701" # forces replacement
      ~ id            = "i-0a1b2c3d4e5f60718" -> (known after apply)
        instance_type = "t3.medium"
      ~ private_ip    = "10.0.1.23" -> (known after apply)
        # (24 unchanged attributes hidden)
    }

  # aws_security_group.web will be updated in-place
  ~ resource "aws_security_group" "web" {
        id      = "sg-0f3a9c2b1d4e5f678"
      ~ ingress = [
          - {
              - cidr_blocks = ["0.0.0.0/0"]
              - from_port   = 22
              - protocol    = "tcp"
              - to_port     = 22
                # (5 unchanged attributes hidden)
            },
            # (1 unchanged element hidden)
        ]
        # (7 unchanged attributes hidden)
    }

Plan: 2 to add, 1 to change, 1 to destroy.
  1. 2 to add means two brand-new resources are being created; the instance is updated in place with the new AMI. A -/+ replacement contributes one add and one destroy to the summary; the # forces replacement comment on ami says the instance is destroyed and recreated, not updated.
  2. Three separate things. Someone added an SSH-from-anywhere rule to the security group in the console; the plan reverts it in place (~) because configuration is the source of truth. Someone deleted the deploy IAM role out of band; refresh dropped it from state and the plan recreates it (+). The AMI filter change forces replacement of the instance (-/+, destroy then create), which is the only change this PR caused and the only one with an outage. The summary counts the replacement as one add and one destroy. Read the 'changed outside' block as what refresh discovered and the actions block as what apply will do; the # forces replacement marker pins the outage to the AMI.
  3. The console-added SSH rule will be kept: Terraform only manages the attributes it set, and the extra rule was added outside Terraform. With inline ingress blocks the whole rule set is a managed attribute; anything not declared in configuration is removed on apply, which is what the - inside the ~ ingress shows.
  4. The plan will fail: Terraform refuses to apply when objects have changed outside of Terraform until you run terraform apply -refresh-only to reconcile state. The drift note is informational; the actions block already incorporates the refreshed state. -refresh-only is for accepting drift into state without changing infrastructure, not a prerequisite.
In short

Apply will revert the console SSH rule, recreate the deleted IAM role, and destroy and recreate the instance for the new AMI; only the instance change causes downtime.

Why

A plan has two halves when drift exists. The first, under Objects have changed outside of Terraform, is a report from refresh: reality differs from the last state, here a security-group rule that appeared and a role that vanished. The second, under Terraform will perform the following actions, is what apply will do given configuration versus that refreshed reality: revert the rule (~), recreate the role (+), and replace the instance (-/+) because ami cannot change on an existing EC2 object. Only the last of these came from the pull request. The interview-grade read names all three, says which one causes downtime, and asks whether the SSH rule and the deleted role were deliberate before applying a plan that undoes them.

The common mistake

Believing Terraform merges or keeps console changes. With inline ingress blocks the whole rule set is managed, so the SSH rule is reverted on apply; and believing drift blocks apply, which it never does.

Read the docs

4 Answer out loud

You inherit one Terraform root module and one state file that manage everything for a product: VPC and networking, IAM, the EKS cluster, RDS, and the roles and queues for about thirty application services. Applies take 25 minutes, every pull request's plan touches hundreds of resources, and a provider upgrade last month blocked all infrastructure changes for two days. How would you redraw the state boundaries, how would you migrate to them without downtime or recreating anything, and what makes a boundary the right one? Three to six sentences.

In short

A strong answer splits state by blast radius and ownership, moves resources with state mv or removed plus import, and proves each move with a no-op plan on both sides.

What a strong answer does
  • boundaries: Boundaries follow blast radius, change cadence, and ownership; dependencies point one way (apps read network and cluster through data sources or a few outputs, never the reverse); each stack has its own backend key, lock, and role; stateful resources are isolated so an application change can never plan their destroy.
  • migration: Pulls state, moves addresses with state mv (or removed plus import blocks) into each new stack's state, pushes, and requires a no-op plan in both source and destination before the next move; migrates one stack at a time behind a freeze on that stack only; puts prevent_destroy and provider deletion protection on stateful resources before starting; notes that moved blocks do not cross root modules.
  • communication: Leads with the criteria, applies them to the concrete inventory, gives the migration with its verification step, and closes with the tradeoff accepted: more roots and more cross-stack plumbing in exchange for a small blast radius.
Why

Staff-level answers state the criteria before the layout: blast radius, change cadence, ownership, and one-directional dependencies. They treat the migration as a verified state operation rather than a rebuild, with a no-op plan on each side as the proof and stateful resources guarded before anything moves. And they name the cost they are accepting. Candidates who reach for workspaces have confused state files with isolation, and candidates who propose recreating resources have not understood that the whole point of state mv, moved, removed, and import is to change Terraform's mapping without changing the cloud.

The common mistake

Reaching for CLI workspaces as the split, or proposing to recreate resources in the new stacks. The whole point of state mv, moved, removed, and import is to change Terraform's mapping without touching the cloud.

Read the docs

5 Find what's broken

Last month someone ran terraform destroy from a laptop believing they were in the dev workspace; deletion_protection is the only reason orders-prod still exists. Separately, an instance-class change made in the console on the prod database three weeks ago has never produced a change in any plan, and a PR that changed allocated_storage applied 'successfully' and changed nothing. Which two lines are responsible?

terraform {
  required_version = "~> 1.6"

  backend "s3" {
    bucket         = "acme-tfstate"
    key            = "platform/terraform.tfstate"
    region         = "us-east-1"
    dynamodb_table = "acme-tfstate-lock"
    encrypt        = true
  }
}

provider "aws" {
  region = "us-east-1"
  assume_role {
    role_arn = "arn:aws:iam::111111111111:role/terraform-admin"
  }
}

locals {
  env     = terraform.workspace
  is_prod = local.env == "prod"
}

resource "aws_db_instance" "orders" {
  identifier          = "orders-${local.env}"
  engine              = "postgres"
  instance_class      = local.is_prod ? "db.r6g.xlarge" : "db.t4g.medium"
  allocated_storage   = local.is_prod ? 500 : 50
  deletion_protection = local.is_prod
  skip_final_snapshot = !local.is_prod
  password            = var.db_password

  lifecycle {
    ignore_changes = all
  }
}
In short

Line 16 assumes one admin role for every workspace, and line 35 (ignore_changes = all) hides every drift and config change from the plan.

What's broken
  • Line 16: One administrative role in one account is assumed for every workspace, so a dev operation and a prod operation run with identical permissions; the wrong-workspace destroy reached production because nothing but the workspace name separated the two.
  • Line 35: ignore_changes = all tells Terraform to ignore every attribute after creation: a console change never becomes a planned change (on Terraform 1.2+ it is not even listed under 'changed outside of Terraform', which only reports drift relevant to the plan), and configuration changes to this resource are silently never applied either.
Why

Two operational faults hiding behind reasonable-looking lines. Line 16 is the workspaces trap in its purest form: workspaces split state, not credentials, so the blast radius of a mistake is the union of every environment the shared role can touch, and deletion_protection (line 30, correct) was doing the job the credential boundary should have done. Line 35 is drift suppression: all means Terraform may create and destroy the object but will never propose an update, so both the console change and the PR's change vanish from every plan. The distractors are fine: the state key (line 6) is per stack, terraform.workspace in a local (line 21) is the workspaces pattern itself rather than the fault, and deletion_protection = local.is_prod (line 30) is the guard that worked.

Read the docs

6 Find what's broken

Two reviewers block this PR on one line each. One says it will destroy the production database; the other says it hands the master password to everyone who can read this state. Which lines, and what does each become?

# PR: "move the orders database into the shared rds-postgres module"
# Before this PR, resource "aws_db_instance" "orders" was declared in this root module.

resource "random_password" "master" {
  length  = 32
  special = false
}

module "orders_db" {
  source          = "git::https://github.com/acme/tf-modules.git//rds-postgres?ref=v2.3.0"
  identifier      = "orders-prod"
  engine_version  = "15"
  instance_class  = "db.m6g.large"
  master_password = random_password.master.result
  subnet_ids      = data.aws_subnets.private.ids
}

moved {
  from = aws_db_instance.order
  to   = module.orders_db.aws_db_instance.this
}

output "orders_db_endpoint" {
  value = module.orders_db.endpoint
}

output "orders_db_password" {
  description = "Read by the app stack through terraform_remote_state"
  value       = random_password.master.result
}
In short

Line 19 misspells the moved from-address, so the database is destroyed and recreated; line 29 outputs the password, so every state reader gets it.

What's broken
  • Line 19: The from address is misspelled (order, not orders). A moved block whose from matches nothing in state is silently a no-op, so the real aws_db_instance.orders is still in state with no configuration (planned destroy) and module.orders_db.aws_db_instance.this is in configuration with no state (planned create).
  • Line 29: Exporting the generated password as a root output turns the state file into a secret-distribution API: every principal that can read this state, including every terraform_remote_state consumer, receives the plaintext, and the value already sits unencrypted in the state document. sensitive = true, which Terraform will demand here because result is sensitive, only hides it from CLI output.
Why

Both faults are about state, not infrastructure. A moved block is an instruction to the planner about identity, and its failure mode is quiet: an unmatched from is legal because moved blocks are meant to stay in the code after the move has happened, so the typo produces the exact destroy-and-create the block existed to prevent. The password output is the state-as-secret-store problem: outputs are the documented interface to remote state, so publishing the value there is publishing it to every consumer, and the sensitive flag changes only what the CLI prints. The distractors are things a reviewer approves: the module pinned to a tag (line 10), passing the generated password into the module (line 14, which is in state regardless of this line), and an endpoint output (line 24) that consumers actually need.

Read the docs

7 Scenario: what do you do next?

You run Terraform for a proof-of-stake validator fleet: 12 cloud validator and sentry instances in AWS, plus 8 bare-metal validators in two colocation sites whose firewall rules and DNS are managed through their providers, all in one validators root module with an S3 backend and DynamoDB locking. At 03:00 the on-call engineer mitigated a DDoS against the bare-metal sites by adding an allow rule in the colo console. Earlier, at 02:14, an unattended CI apply was killed when its runner was recycled. It is 09:00 and the morning CI plan job fails immediately.

Step 1. The job output ends with Error acquiring the state lock. Lock Info: ID: 7f2c..., Operation: OperationTypeApply, Who: ci@runner-7, Created: 02:14. A teammate suggests terraform force-unlock 7f2c... right away. What do you do first?

  1. Delete the lock item from the DynamoDB table by hand so the pipeline can proceed. Same effect as force-unlock without the lock-ID check or the audit trail, and it invites deleting the wrong item; use the command that exists for this.
  2. Re-run the plan job with -lock=false so it does not need the lock at all. That disables the protection for this run instead of clearing a stale lock, and it teaches the pipeline a flag that must never be there.
  3. Confirm the holder is dead: runner-7 no longer exists and CI shows no running job for this stack. Then terraform force-unlock 7f2c.... Before planning, terraform state pull and compare the serial with the 02:14 job log to learn whether the killed apply wrote state or left objects created but unrecorded. force-unlock is safe exactly when the holder cannot still be writing; the lock info tells you who to check. Knowing whether the interrupted apply recorded its work tells you whether the coming plan will contain phantom creates.
  4. Run terraform force-unlock 7f2c... immediately; locks are advisory and the plan is blocking the team. If the 02:14 process were somehow still applying, two writers would race and one would silently overwrite the other's state, which is the exact failure the lock prevents. Ten seconds of checking the runner costs nothing.

Step 2. The lock is cleared and the plan runs: ~ on all 8 bare-metal firewall resources (removing the 03:00 allow rule), -/+ on 3 of the 12 cloud validator instances because data.aws_ami.validator now resolves to a newer image, + on one DNS record. Plan: 4 to add, 8 to change, 3 to destroy. The validator lead says: 'Config is the source of truth, apply it.' What do you do?

  1. Run terraform apply -refresh-only to accept the drift into state, then apply the rest. refresh-only records the console rule in state, but the configuration still lacks it, so the very next plan reverts it again; and it does nothing about the -/+, which is a configuration-versus-state change, not drift.
  2. Apply now: drift only gets worse the longer it sits, and the AMI update is overdue anyway. Drift does not decay; the plan will be identical tomorrow. Replacing 3 validators at once with an image change nobody reviewed is an outage you scheduled by accident, and the firewall revert reopens the attack surface.
  3. Do not apply this plan. Codify the 03:00 firewall rule (add it to configuration, or make it a variable) after confirming with the on-call that it should stay; pin data.aws_ami.validator to the image id the 9 healthy validators run so the -/+ disappears, and schedule the image upgrade as its own PR that rolls one validator at a time; let the DNS + through. Re-plan and expect only the changes you chose. Config is the source of truth as a policy; the plan is where you decide what the config should say. Reverting an anti-DDoS rule and replacing three validators nobody asked to replace is drift turned into downtime and missed blocks.
  4. Add lifecycle { ignore_changes = all } to the firewall and instance resources so the plan is clean, then apply. That hides every future change to those resources, including hostile ones, and freezes the validators against legitimate updates. The fix is to make the configuration say what you mean.

Step 3. You end the day with a clean plan and no validators replaced. For the postmortem, what systemic change do you propose?

  1. Split validators by blast radius (bare-metal firewall and DNS; cloud validators; sentries); pin the validator image to an explicit id promoted by PR instead of a most_recent data source; prevent_destroy on validator hosts and their volumes; plan output on every PR with a CI check that fails on - or -/+ touching validator or firewall resources unless labelled; and a final on-call runbook step: a PR that codifies any console change within 24 hours. Mechanisms at every layer: smaller state so a lock or a bad plan cannot touch everything, no floating input that can rewrite the fleet, destructive changes made visible and deliberate, and drift codification made routine instead of heroic.
  2. Merge the sentries and RPC nodes into the same root module so there is one source of truth for the whole fleet. A bigger state is a bigger blast radius: one stuck lock, one provider bug, or one bad plan then blocks or endangers everything at once.
  3. Forbid console changes; everything goes through Terraform, even during incidents. At 03:00 under a DDoS you want the on-call to make the console change. The mechanism is to codify it afterwards, not to forbid the mitigation.
  4. Add a nightly terraform apply -auto-approve so drift never accumulates. That automates the exact failure: unreviewed reverts and unreviewed replacements applied to a validator fleet while nobody is watching.
In short

Confirm the lock holder is dead before force-unlocking, do not apply a plan full of drift and surprise replacements, and split the state by blast radius.

Why

Three decisions interviewers score, none of them chain-specific. A lock is cleared only after you know the holder is dead, and an interrupted apply means checking whether state recorded its work. A plan with drift and unintended replacements is not a plan to apply or to suppress; it is a list of decisions, and each ~ and -/+ gets its own answer (codify, pin, or accept). The systemic fix removes the mechanisms that produced the surprise: floating inputs, one giant state, and destructive changes that nothing forces a human to read. On a validator fleet the cost of getting it wrong is explicit, missed attestations and reopened attack surface, but the same plan-reading discipline applies to any stateful fleet.

Read the docs

8 Quick recall

Someone built the production NAT gateway by hand last year and it now has to live in Terraform. Which operation binds that existing object to a resource address in state without creating, changing, or destroying it?

In short

The answer is terraform import (or an import block).

Accepted

import · terraform import · import block

Why

terraform import <address> <id> (or an import {} block) writes the object's identity and current attributes into state and touches nothing in the cloud; the configuration is then adjusted until plan shows no changes. moved is the sibling operation for objects that are already in state under a different address.

Read the docs

That's the last lesson in mission 08 Pick your next mission
Drill · Terraform in operation
0:00

Loading…