The Analogy: The Set-Dressing Crew and the Continuity Reference
On a long film shoot, a standing set -- a detective's office used for weeks -- has to be returned to a known state every shooting morning so the footage cuts together cleanly. The crew is not handed a list of moves to perform. They are handed a reference: a set-dressing plan and continuity stills that show exactly what must be on the set and where -- the ledger on the desk, the coat on the hook, three files in the tray. Their instruction is simply "make the room look like this." Describing the desired end result rather than the steps to reach it is the whole idea of a declarative configuration, and it is exactly how you tell Terraform what infrastructure should exist.
The lead dresser walks the set holding the reference and compares every surface to it, noting what is missing to add, what is extra to remove, and what sits wrong to correct. That walk-through is done first, on a clipboard, before a single object is touched -- it is a preview of the work, not the work itself. Only then does the crew execute the punch list. And if the set already matches the reference, the walk-through produces an empty list and nobody moves anything: doing the reset a second time changes nothing, because the reset is defined by the target state, not by a script that runs blindly.
None of this is possible until the right pieces are on hand. Before the walk, a runner draws the specified items from the prop house -- the exact period telephone, the correct coat, that particular ledger -- because you cannot dress a set to a plan using props you have not pulled. Loading the correct catalog of pieces is a separate, up-front step, and if the prop house cannot supply a called-for item at the version the plan specifies, the reset stalls before it can even begin.
The failure is quiet, and it ships straight to camera. A dresser in a hurry checks only that the mantel holds the right number of objects -- five items, counts to five, ticks it off -- and signs the set off as matching the reference. But overnight a hero prop was swapped for a look-alike of the same size. The count is unchanged, so the coarse check passes, and the continuity error rolls through the whole day's footage unnoticed. The set was never truly reconciled to the reference; it was reconciled to a tally, and a tally is exactly the kind of check a real difference can slip straight past.
Syntax or Core Structure
Terraform configuration is declarative HCL. You write resource blocks describing the infrastructure you want to exist; Terraform reads the current state, compares it to your configuration, and computes the create, update, and delete actions that make reality match. You never write the API calls yourself. A minimal configuration names a provider and one or more resources:
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 5.0"
}
}
}
provider "aws" {
region = "us-east-1"
}
resource "aws_s3_bucket" "assets" {
bucket = "acme-assets"
}
resource "aws_s3_bucket" "logs" {
bucket = "acme-logs"
}
With the configuration written, the whole lifecycle runs through four commands, and only two of them ever change anything:
terraform init # download the providers named above
terraform plan # show the diff between config and reality; changes nothing
terraform apply # execute that diff to converge reality to the config
terraform destroy # remove every resource this config manages
The engine underneath is simpler than it looks: a plan is a three-way diff. Resources present in the config but not in reality are added, resources in both but differing are changed, and resources in reality but no longer in the config are destroyed. This small reconciler behaves exactly like that core for a first apply against an empty world:
DESIRED = {
'aws_s3_bucket.assets': {'bucket': 'acme-assets', 'acl': 'private'},
'aws_s3_bucket.logs': {'bucket': 'acme-logs', 'acl': 'private'},
}
current = {} # nothing exists yet
def plan(desired, current):
add = sorted(k for k in desired if k not in current)
change = sorted(k for k in desired if k in current and desired[k] != current[k])
destroy = sorted(k for k in current if k not in desired)
return add, change, destroy
def apply(desired, current):
add, change, destroy = plan(desired, current)
for k in add + change:
current[k] = dict(desired[k])
for k in destroy:
del current[k]
return len(add), len(change), len(destroy)
add, change, destroy = plan(DESIRED, current)
print('plan: +%d add ~%d change -%d destroy' % (len(add), len(change), len(destroy)))
for k in add:
print(' + %s' % k)
a, c, d = apply(DESIRED, current)
print('apply complete: %d added, %d changed, %d destroyed' % (a, c, d))
print('resources now managed: %d' % len(current))
Output:
plan: +2 add ~0 change -0 destroy
+ aws_s3_bucket.assets
+ aws_s3_bucket.logs
apply complete: 2 added, 0 changed, 0 destroyed
resources now managed: 2
The plan is printed and reviewed before anything happens -- that is the safety of the workflow. apply then performs exactly the two creations the plan promised, and the state now tracks two managed resources. Nothing here depends on the order you wrote the blocks or on what ran before; the same configuration against the same reality always yields the same plan.
Technical Depth: What "Declarative" Buys You
Imperative steps versus a declared end state
The difference between a shell script that provisions infrastructure and a Terraform configuration is not syntax; it is who owns the diff. An imperative script lists the operations to perform and trusts that the world is in the state those operations expect. A declarative configuration states the target and lets the tool work out the operations.
| Imperative script | Declarative config |
|---|---|
| Lists the steps to run | Describes the end state |
| Breaks or duplicates if run twice | Safe to run repeatedly |
| You track what already changed | The tool computes the diff |
| You sequence the operations | The tool orders by dependency |
The practical payoff of declaring the end state is idempotence: because every run recomputes the diff from scratch, applying an unchanged configuration is a guaranteed no-op, and applying a changed one touches only what actually differs. The reconciler shows both cases -- a re-plan on already-converged state, then a single attribute edit:
DESIRED = {
'aws_s3_bucket.assets': {'acl': 'private'},
'aws_s3_bucket.logs': {'acl': 'private'},
}
current = {k: dict(v) for k, v in DESIRED.items()} # state right after the first apply
def plan(desired, current):
add = sorted(k for k in desired if k not in current)
change = sorted(k for k in desired if k in current and desired[k] != current[k])
destroy = sorted(k for k in current if k not in desired)
return add, change, destroy
print('re-plan on converged state:')
a, c, d = plan(DESIRED, current)
print(' +%d ~%d -%d (idempotent: nothing to do)' % (len(a), len(c), len(d)))
DESIRED['aws_s3_bucket.assets']['acl'] = 'public-read'
a, c, d = plan(DESIRED, current)
print('after editing acl, plan: +%d ~%d -%d' % (len(a), len(c), len(d)))
for k in c:
print(' ~ %s (%s -> %s)' % (k, current[k]['acl'], DESIRED[k]['acl']))
Output:
re-plan on converged state:
+0 ~0 -0 (idempotent: nothing to do)
after editing acl, plan: +0 ~1 -0
~ aws_s3_bucket.assets (private -> public-read)
The first plan finds nothing because config and reality already agree, so an apply here would change nothing at all. The moment one attribute is edited, the very same diff logic reports exactly one change and names the old and new value, which is what you review before applying. This is why Terraform can be run on a schedule without fear: an unchanged world costs one harmless plan.
Real World Example: The Drift Check That Counted Resources
A platform team wanted a nightly job to answer one question: does our live AWS account still match what Terraform declares? Rather than run a real plan, someone wrote a quick check that compared the number of managed resources in the configuration to the number found in the account, reasoning that if the counts matched, nothing had drifted. It ran green for months. Then an on-call engineer, firefighting at 2 in the morning, flipped a storage bucket to public-read in the console to unblock a download and never reverted it. Here is what the nightly job saw:
DESIRED = {
'aws_s3_bucket.assets': {'acl': 'private', 'versioning': 'enabled'},
'aws_s3_bucket.logs': {'acl': 'private', 'versioning': 'enabled'},
'aws_security_group.web': {'ingress': '443', 'egress': 'all'},
}
actual = {
'aws_s3_bucket.assets': {'acl': 'public-read', 'versioning': 'enabled'}, # edited by hand
'aws_s3_bucket.logs': {'acl': 'private', 'versioning': 'enabled'},
'aws_security_group.web': {'ingress': '443', 'egress': 'all'},
}
def naive_in_sync(desired, actual):
return len(desired) == len(actual) # compares resource COUNT only
def real_plan(desired, actual):
changed = []
for k in sorted(desired):
if k in actual and desired[k] != actual[k]:
diffs = sorted(a for a in desired[k] if desired[k][a] != actual[k].get(a))
changed.append((k, diffs))
return changed
print('desired resources: %d actual resources: %d' % (len(DESIRED), len(actual)))
print('naive checker (counts only) says in sync: %s' % naive_in_sync(DESIRED, actual))
changed = real_plan(DESIRED, actual)
print('real plan finds %d resource(s) drifted:' % len(changed))
for k, diffs in changed:
for a in diffs:
print(' ~ %s.%s: %s -> %s' % (k, a, actual[k][a], DESIRED[k][a]))
print('drift missed by the naive checker: %s' % (naive_in_sync(DESIRED, actual) and len(changed) > 0))
Output:
desired resources: 3 actual resources: 3
naive checker (counts only) says in sync: True
real plan finds 1 resource(s) drifted:
~ aws_s3_bucket.assets.acl: public-read -> private
drift missed by the naive checker: True
The account still holds exactly three resources, so the count-based check reports "in sync" and the nightly job stays green. But a real plan compares every attribute of every resource, and it immediately finds that assets has drifted: its acl is public-read in reality where the configuration declares private. The drift a real plan would have caught -- and offered to revert -- sailed straight past the counter, and a bucket meant to be private served the public for weeks.
The design flaw is the sync key. naive_in_sync collapses the entire state to a single integer, the resource count, and cardinality is invariant under exactly the change that matters most: an in-place edit that neither adds nor removes a resource. Any drift that keeps the count constant -- a loosened security group, a flipped ACL, a widened IAM policy -- is structurally invisible to it. real_plan is not cleverer, only more thorough: it descends to attributes, which is precisely the granularity at which Terraform itself operates, and it is why a real plan, not a tally, is the thing you schedule.
The model is still a teaching sketch, and its limits are worth naming. It assumes it can read the account's true state perfectly, when Terraform leans on a state file and a refresh that can itself be stale. It compares attributes with plain dictionary equality, ignoring the provider-side normalization, computed values, and defaults that make real diffs subtler and sometimes noisier than this. And it treats every difference as an in-place update, whereas some attribute changes force a destroy-and-recreate that a careful operator must catch before approving.
Finally, it only ever looks at resources the configuration already names. A resource created entirely outside Terraform is absent from DESIRED and so is invisible to real_plan here, even though it is real drift of a different kind -- ironically the one case where a raw count of everything in the account might notice something the config-scoped diff does not. The honest takeaway is that no single cheap check substitutes for an attribute-level plan run against trustworthy state.
Common Mistakes
- Making changes in the console instead of the configuration. An out-of-band edit creates drift that the next apply will try to undo, and it silently breaks the guarantee that the configuration describes reality.
- Running apply without reading the plan. apply re-runs plan first, but auto-approving means nobody sees the diff; a typo that destroys a database looks identical to a safe change until it has already happened.
- Hardcoding values that differ per environment. A baked-in region or bucket name forces copy-pasted configurations that drift apart over time; anything environment-specific belongs in a variable.
- Assuming a resource rename is free. Changing a resource's name in the configuration makes Terraform destroy the old resource and create a new one, not rename it in place, so a careless rename can quietly delete a live database.
- Treating plan as an optional step. The plan is the entire safety mechanism of the workflow; skipping straight to an auto-approved apply in a hurry is how accidental destroys reach production.
- Leaving provider versions unpinned. An unpinned provider can upgrade underneath you and change plan output or resource behavior between two runs of the very same configuration.
- Confusing matching counts with being in sync. As the example showed, equal resource counts say nothing about attributes; only an attribute-level plan detects an in-place edit.
- Forgetting to run init after adding a provider or module. New providers and modules are downloaded only by init; plan and apply will fail or use stale code until you re-run it.
- Committing state or secret variable files to Git. State files and variable files holding credentials are not source; committing them leaks secrets and invites conflicts that corrupt your record of reality.
Best Practices
- Keep all infrastructure in version-controlled configuration and change it only by editing that configuration, never by clicking in the console.
- Always review the plan before you apply, and require a human to approve it for anything that touches production.
- Parameterize everything environment-specific with variables so one configuration serves dev, staging, and production unchanged.
- Pin provider and module versions so the same configuration produces the same plan tomorrow that it does today.
- Run plan on a schedule or in CI to surface drift early, comparing at the attribute level rather than by counting resources.
- Make small, frequent changes and apply them often, because a large batched apply is harder to review and riskier to roll back.
- Enforce terraform validate and formatting checks in CI so broken or unformatted configuration never merges.
- Tear down throwaway environments with terraform destroy rather than deleting resources by hand, so state and reality never diverge.
Practice Exercises
- Write a minimal configuration with a provider and two resources, run plan, and read the diff before applying. Apply it, then run plan a second time and confirm the plan reports no changes, proving the workflow is idempotent.
- Introduce a variable for an environment name, reference it from a resource, and apply the same configuration twice with two different variable values. Explain exactly what Terraform creates, changes, or destroys on the second apply and why.
- Extend the count-based drift checker from the Real World Example so it descends to attributes. Feed it a state where one resource's attribute has drifted but the resource count is unchanged, and show that your version reports the drift the count check missed.
- Rename a resource in your configuration and run plan. Explain why Terraform proposes a destroy-and-create rather than a rename, and describe the state operation that would preserve the existing resource instead.