State Management & Remote Backends

State Management & Remote Backends in DevOps Tools: --- A bank that rents safe-deposit boxes does not actually know what is inside each box, but it must know,…


The Analogy: A Bank's Safe-Deposit Vault and Its Master Register

A bank that rents safe-deposit boxes does not actually know what is inside each box, but it must know, with total certainty, which numbered box belongs to which renter and which key opens it. That knowledge lives in one place: the master register, a single authoritative book that maps box 214 to a renter, a lock type, and a rental status. The boxes are the real assets sitting in the steel-lined vault; the register is the bank's model of that reality. Every time a clerk rents, closes, or re-keys a box, the true first-class act is not touching the steel -- it is amending the register so the book still describes the vault exactly. Lose the register and the bank still has a room full of locked boxes, but it no longer knows whose is whose, and it cannot safely touch a single one.

Because the register is the source of truth, where it lives matters enormously. A junior clerk who keeps his own private copy in his desk drawer is a disaster waiting to happen: his copy drifts from everyone else's, and when he is on holiday nobody else can rent a box. Serious banks keep exactly one register, inside the vault itself, fireproof and access-controlled, and every clerk works against that one copy. This is the difference between scribbling infrastructure state into a file on your laptop and storing it in a shared, durable, encrypted location that the whole team reads from and writes to.

Amending the register is never a free-for-all. When a clerk opens the register to change an entry, he first signs it out under a dual-control lock: while he holds it, no second clerk may write to it. The second clerk is not turned away forever -- he simply waits until the book is signed back in, then makes his change on top of the first clerk's, so both amendments survive. Remove that discipline and let two clerks scribble into two separate photocopies at the same instant, and whoever files his copy last silently erases the other's entry. The box he rented is still physically in the vault, occupied, but the register no longer mentions it.

That last scenario is the failure mode worth dwelling on. Suppose a locksmith re-keys box 214 at a customer's urgent request one evening and simply forgets to tell the front desk. The steel box now has a new lock, but the register still records the old one. Nothing looks wrong: the box count is unchanged, every entry still points at a real box, and a clerk who only counts entries will swear the register is accurate. The register and the vault have quietly diverged, and the discrepancy surfaces only at the worst possible moment -- when someone trusts the book, brings the wrong key, and cannot open the box. A register that is merely present is not the same as a register that still tells the truth.


Syntax or Core Structure

Terraform's state is a JSON document that maps every resource address in your configuration (like aws_instance.web) to the real object it created in the cloud, recording that object's id and attributes. On the first terraform apply, Terraform creates the resources and writes that mapping. On every later run it reads the state to answer one question -- what already exists -- so that it changes only the difference. The default terraform.tfstate on local disk is fine for one person; a team must move it to a shared remote backend.

# backend.tf -- one shared, encrypted, lockable state in S3
terraform {
  backend "s3" {
    bucket         = "acme-terraform-state"
    key            = "prod/network/terraform.tfstate"
    region         = "us-east-1"
    encrypt        = true
    dynamodb_table = "terraform-locks"
  }
}

The dynamodb_table is what turns a shared file into a safe shared file: before writing, Terraform inserts a lock row keyed by the state path and refuses to proceed if one already exists. To see how the state behaves as a map, here is a tiny model in Python that records an address-to-id entry per created resource and then lists them the way terraform state list does -- sorted.

DESIRED = ['aws_vpc.main', 'aws_subnet.public', 'aws_instance.web', 'aws_s3_bucket.assets']

def fake_id(addr, n):
    kind = addr.split('.')[0].replace('aws_', '')
    return '%s-%04d' % (kind, n)

state = {}
for i, addr in enumerate(DESIRED, start=1):
    state[addr] = fake_id(addr, i)     # apply: create resource, record address -> id

print('resources in state: %d' % len(state))
for addr in sorted(state):             # terraform state list prints sorted
    print('  %s' % addr)
one = 'aws_instance.web'
print('state show %s -> id %s' % (one, state[one]))

Output:

resources in state: 4
  aws_instance.web
  aws_s3_bucket.assets
  aws_subnet.public
  aws_vpc.main
state show aws_instance.web -> id instance-0003

Technical Depth: Locking, Inspection, and Surgical State Edits

The state subcommands you actually use

Terraform gives you commands to read and rewrite the register directly. You reach for them rarely, but when you do, precision matters -- state rm in particular forgets a resource without destroying it.

terraform state list                                 # every managed address, sorted
terraform state show aws_instance.web                # full recorded attributes of one
terraform state mv aws_instance.web aws_instance.api # rename without recreate
terraform state rm aws_s3_bucket.assets              # forget (do NOT destroy) a resource
terraform state pull > backup.tfstate                # download the current remote state
CommandTouches real cloud?Typical use
state listNoAudit what is managed
state showNoInspect recorded attributes
state mvNoRename or move into a module
state rmNoHand a resource to another config
importNoAdopt an existing cloud resource

Notice that none of these change infrastructure -- they edit only the register. A state rm followed by a plan makes Terraform propose creating the resource again, because it now believes the resource does not exist.

Why the lock is not optional

The lock exists so that two applies cannot interleave their read-modify-write of the state. Here is a deterministic model of the healthy path: pipeline-2 arrives while pipeline-1 holds the lock, is refused, waits, and then applies its change on top of pipeline-1's committed state, so both writes survive.

shared = {'aws_vpc.main': 'vpc-0001'}
lock_holder = [None]
log = []

def acquire(who):
    if lock_holder[0] is None:
        lock_holder[0] = who
        return True
    return False

def release(who):
    if lock_holder[0] == who:
        lock_holder[0] = None

acquire('pipeline-1')
p1_view = dict(shared)                        # read state under the lock
if not acquire('pipeline-2'):                 # pipeline-2 arrives, is refused
    log.append('pipeline-2: blocked, lock held by %s' % lock_holder[0])
p1_view['aws_subnet.public'] = 'subnet-0002'
shared.clear(); shared.update(p1_view)        # pipeline-1 writes, then releases
log.append('pipeline-1: wrote aws_subnet.public (state has %d)' % len(shared))
release('pipeline-1')
acquire('pipeline-2')                         # pipeline-2 retries, now succeeds
p2_view = dict(shared)                        # reads the UPDATED state
p2_view['aws_instance.web'] = 'instance-0003'
shared.clear(); shared.update(p2_view)
log.append('pipeline-2: wrote aws_instance.web (state has %d)' % len(shared))
release('pipeline-2')

for line in log:
    print('  ' + line)
print('final resources in state: %d' % len(shared))
print('both writes preserved: %s' % (len(shared) == 3))

Output:

  pipeline-2: blocked, lock held by pipeline-1
  pipeline-1: wrote aws_subnet.public (state has 2)
  pipeline-2: wrote aws_instance.web (state has 3)
final resources in state: 3
both writes preserved: True

Because the lock serialized the two applies, pipeline-2 read pipeline-1's committed state (two resources) before adding the third, so nothing was lost. The next section shows what those same two applies do when the lock is turned off.


Real World Example: A CI Race That Silently Orphans a Resource

A team runs terraform apply from CI on every merge. To speed up a busy day, someone adds -lock=false so builds stop queueing behind one another. Two merges land within the same second, and two applies run against the same base state at once. Each reads the state, creates its own resource in the cloud, and writes the state back. Both exit 0, and the pipeline dashboard is entirely green. The program below models that race and then the repair.

cloud = {'aws_vpc.main': 'vpc-0001'}
state = {'aws_vpc.main': 'vpc-0001'}
base = dict(state)

cloud['aws_subnet.public'] = 'subnet-0002'    # pipeline-1 creates a subnet
p1_state = dict(base); p1_state['aws_subnet.public'] = 'subnet-0002'

cloud['aws_instance.web'] = 'instance-0003'   # pipeline-2 creates an instance
p2_state = dict(base); p2_state['aws_instance.web'] = 'instance-0003'

exit1, exit2 = 0, 0
state.clear(); state.update(p1_state)         # pipeline-1 writes state first
state.clear(); state.update(p2_state)         # pipeline-2 writes LAST, clobbering it

orphans = sorted(a for a in cloud if a not in state)
print('apply exit codes: pipeline-1=%d  pipeline-2=%d' % (exit1, exit2))
print('cloud resources: %d   state resources: %d' % (len(cloud), len(state)))
print('naive check (both exited 0) says success: %s' % (exit1 == 0 and exit2 == 0))
print('state consistent with cloud: %s' % (len(orphans) == 0))
for a in orphans:
    print('  orphan (in cloud, absent from state): %s = %s' % (a, cloud[a]))

for a in orphans:                             # terraform import re-adopts the orphan
    state[a] = cloud[a]
print('after terraform import: state resources: %d' % len(state))
print('state consistent with cloud: %s' % (sorted(state) == sorted(cloud)))

Output:

apply exit codes: pipeline-1=0  pipeline-2=0
cloud resources: 3   state resources: 2
naive check (both exited 0) says success: True
state consistent with cloud: False
  orphan (in cloud, absent from state): aws_subnet.public = subnet-0002
after terraform import: state resources: 3
state consistent with cloud: True

Both applies genuinely succeeded in the only sense that CI measured: each command exited 0, and each created its resource in the cloud. But because -lock=false let them run concurrently, they both branched from the same base state, and pipeline-2's write landed last and overwrote pipeline-1's. The subnet is real, running, and billable, yet the state no longer mentions it. It is an orphan: the next plan will try to create it again and may fail with an "already exists" error, or worse, build a duplicate.

The repair is terraform import aws_subnet.public subnet-0002, which re-adopts the live resource into the register without recreating it. After the import the state holds all three resources and matches the cloud again. Note that import is a manual, one-resource-at-a-time rescue -- it is what you do after the accident, not protection against it.

This example is deliberately simplified in ways worth naming. Real state writes are not literal last-writer-wins dictionary overwrites; S3 with versioning plus Terraform's own state serial can sometimes reject a stale write, and terraform plan refreshes against the cloud, so drift is often caught on the next run rather than never. The orphan here is also cleanly importable because it has a stable id; a resource with a generated name, or one that a later apply has already mutated, is far messier to reconcile.

The genuine design flaw, though, is the success check itself, and it survives all of those caveats: judging an apply purely by its exit code is invariant under the lost write. Turning off the lock was the trade the team made for speed, and the exit-0 signal cannot see the cost. A correct gate would keep locking on so the applies serialize and nothing is lost in the first place, and, as defense in depth, compare the post-apply state resource count against the cloud -- exactly the count-plus-attributes reconciliation that a green exit code throws away.


Common Mistakes

  1. Committing terraform.tfstate to Git. State routinely captures plaintext secrets (database passwords, generated keys) as resource attributes, so committing it leaks credentials into history; it also guarantees merge conflicts that no text merge can safely resolve.
  1. Keeping state on one engineer's laptop. A local backend makes that laptop a single point of failure: nobody else can apply, and a disk loss erases Terraform's memory of live infrastructure even though the infrastructure keeps running.
  1. Running with -lock=false to avoid waiting. Disabling the lock lets two applies interleave their read-modify-write and silently drop one write, orphaning real resources -- the exact race modelled above. The queue you were avoiding is far cheaper than the orphan you create.
  1. Assuming a green apply means state is correct. Exit code 0 means the command ran, not that state matches reality. Concurrency, partial failures, and out-of-band edits all leave a zero exit code untouched while the register quietly drifts.
  1. Using terraform destroy when you meant state rm. destroy deletes the real cloud resource; state rm only makes Terraform forget it. Reaching for the wrong one either tears down live infrastructure or leaves a resource you meant to remove still running and now unmanaged.
  1. Editing terraform.tfstate by hand. The file has interdependent serial numbers, lineage, and dependency links; hand-editing the JSON corrupts those invariants and can make the whole state unreadable. Use the terraform state subcommands, which keep the bookkeeping consistent.
  1. Not enabling encryption or versioning on the state bucket. Without encrypt = true the secrets in state sit in plaintext at rest; without bucket versioning a bad write or accidental delete is unrecoverable, because there is no earlier copy to roll back to.
  1. Making console changes and never importing them. Every click in the web console that Terraform did not make is drift: the resource exists but the state does not know it, so a future apply may delete or duplicate it. If you must click, import it back afterward.
  1. Storing every environment in one state file. A single monolithic state means a fat-fingered prod apply and a dev apply fight over the same lock and share one blast radius. Separate state per environment (via distinct keys or workspaces) contains the damage.

Best Practices

  • Store state in a shared remote backend with encryption at rest and object versioning enabled, so the whole team reads one durable copy and any bad write is recoverable.
  • Always keep state locking on (for example, a DynamoDB lock table paired with the S3 backend) and treat -lock=false as a break-glass action, never a default.
  • Give each environment and each independently deployable component its own state key, so blast radius and lock contention both stay small.
  • Never commit state to version control; add *.tfstate* to .gitignore and rely on the backend for durability and history.
  • Reconcile out-of-band changes promptly with terraform import to adopt them, or by reverting the manual change, so the register never drifts far from the vault.
  • Take a terraform state pull backup before any risky state mv or state rm, so a mistaken surgical edit can be restored.
  • Restrict who and what can write to the state bucket and lock table with least-privilege IAM, since write access to state is effectively write access to all your infrastructure.
  • Run terraform plan in CI on every change and require a clean, reviewed plan before apply, so drift and unintended diffs are caught before they reach the vault.

Practice Exercises

  1. Configure an S3 remote backend with a DynamoDB lock table for a small configuration, then start two terraform apply commands from two terminals at once and observe the second one blocking on the lock. Record the lock message it prints.
  1. Create a resource, run terraform state rm on it, and then run terraform plan. Explain in writing why the plan now proposes to create a resource that is still running in the cloud, and how this differs from terraform destroy.
  1. Manually create a resource in the cloud console, then bring it under Terraform management with terraform import and confirm with terraform plan that no changes are proposed. Note which attributes you had to add to the configuration to make the plan clean.
  1. Modelling exercise: extend the CI-race program so that, instead of comparing exit codes, it compares the post-apply state resource count against the cloud count, and show that this check reports the orphan the exit-code check missed.