Field Notes: Infrastructure Changes Without Surprises
Lessons from infrastructure code that went wrong in production, grouped by the mistake they prevent. Each is short; the linked lessons have the details.
Read every plan like a diff of production
- Read the summary line first:
Plan: 1 to add, 0 to change, 14 to destroy.on a one-line change means stop. - Search the plan for
-/+,must be replacedandforces replacement. A replaced database, volume, load balancer or DNS zone is an outage or data loss (Resources & Meta-Arguments). - Check
(known after apply)on things that shouldn't change, e.g. a security group id: it means the group is being recreated and everything attached to it moves. - An
update in-placeoftagson 300 resources is usually harmless; anupdate in-placeofuser_datamay reboot or replace instances, depending on the resource. Read the provider docs for the arguments you touch.
The session shows a habit worth automating: summarise a plan by action before reading the details.
bash · try it yourself
mkdir p && cd p
cat > main.tf <<'HCL'
resource "terraform_data" "svc" {
for_each = toset(["api", "worker", "cron", "billing"])
input = "${each.key}-v1"
}
resource "local_file" "cfg" {
for_each = toset(["api", "worker"])
filename = "${each.key}.cfg"
content = "v1\n"
}
HCL
tofu init >/dev/null && tofu apply -auto-approve >/dev/null
# a "small refactor": billing removed, config content changed, one input changed
cat > main.tf <<'HCL'
resource "terraform_data" "svc" {
for_each = toset(["api", "worker", "cron"])
input = each.key == "cron" ? "cron-v2" : "${each.key}-v1"
}
resource "local_file" "cfg" {
for_each = toset(["api", "worker"])
filename = "${each.key}.cfg"
content = "v2\n"
}
HCL
tofu plan -out=tfplan >/dev/null
tofu show -json tfplan | jq -r '.resource_changes[] | select(.change.actions != ["no-op"])
| "\(.change.actions | join("+") | if . == "delete+create" or . == "create+delete" then "REPLACE" else ascii_upcase end)\t\(.address)"' | sortDELETE terraform_data.svc["billing"]
REPLACE local_file.cfg["api"]
REPLACE local_file.cfg["worker"]
UPDATE terraform_data.svc["cron"]
Two replacements and a delete in a "small refactor": exactly what the pull-request comment should make obvious.
Blast radius
- Small states. Split by component and environment (What State Is). A plan that takes 15 minutes and touches 2,000 resources gets rubber-stamped.
- Prod is a different account. Separate AWS accounts per environment, separate backends, separate roles. A dev pipeline physically can't change prod.
- Guard the irreplaceable with
prevent_destroy,deletion_protection(RDS, load balancers), S3 versioning and Object Lock where needed, and a CI policy that blocks deletes of stateful types (Plan on Pull Request). - Never
-targetyour way through a change except to recover; a targeted apply leaves the rest of the plan for an unsuspecting colleague.
Secrets
- State and plan files contain secrets. Encrypt (backend encryption, and OpenTofu state encryption), restrict access, keep plan artifacts short-lived.
- Prefer designs where secrets never pass through IaC: RDS
manage_master_user_password, IAM roles instead of keys, ephemeral values and write-only arguments. sensitive = trueis redaction, not protection. CI logs withTF_LOG=DEBUGprint everything; never enable debug logs in shared pipelines.
Versions and upgrades
- Pin the CLI (
required_version, tenv files, the CI setup action), providers (~>plus the committed lock file) and modules (registryversion, Git?ref=tags). - Upgrade one thing at a time, in a dedicated pull request:
init -upgradefor one provider, read the changelog's breaking changes, plan every environment, expect zero changes (or explain each one). - Major provider upgrades (AWS 5 → 6) come with an upgrade guide. Do them early in dev, then promote.
Refactoring
- Every rename, move into a module, or
count→for_eachconversion gets amovedblock in the same pull request (moved & removed). The plan must say "has moved", never destroy/create. - Import before you rewrite: when adopting hand-made resources, first make the plan show only imports, then improve the code in later pull requests (Importing).
Operating it
- Run a scheduled drift plan per state and treat drift as an incident to understand, not something to
applyaway blindly (Drift & Refresh). - When an apply fails half-way, don't panic and don't re-run blindly: the state records what was created. Read the error, fix the cause, plan again; the plan shows exactly what is left.
- A stuck lock: find the owner (
Who,Operation, the CI run) beforeforce-unlock(Locking). - Tag everything (
default_tags) with owner, environment and repository. The resource someone finds in the console at 3 a.m. should say where its code lives. - Delete what you create: practice environments with NAT gateways, EKS clusters and databases cost real money every hour.
destroythe same day.
Test yourself
A one-line change produces Plan: 1 to add, 0 to change, 14 to destroy. What should you do?
- Apply: the plan knows best
- Stop and find out why 14 resources would be destroyed before applying anything
- Apply with -target to skip the destroys
- Run apply twice
An apply failed half-way through. What is the right next step?
- Delete the state and start again
- Read the error, fix the cause, run plan again: state records what was already created
- Run force-unlock and apply with -auto-approve
- Destroy everything
Why upgrade providers in a dedicated pull request?
- Registries require it
- So any plan changes can be attributed to the upgrade and reviewed on their own
- To make the lock file smaller
- It is faster