Subscribe

When live AWS is ahead of Terraform: reconciling drift without destroying anything

Fixes often land in the console or CLI first. Our Terraform still said backup retention 0 while production ran with 14, so one apply would have switched backups off. How I list live changes, correct the code to match the account, and stop a plan that deletes.

When live AWS is ahead of Terraform: reconciling drift without destroying anything

Our production RDS instance keeps 14 days of automated backups. The Terraform file for it said backup_retention_period = 0. Backups had been switched on from the console, out of band, and nobody went back to the file. So the code was a trap: the first person to run terraform apply on that root would have turned production backups off, and Terraform would have called it a normal update. Plan output would show one line, ~ backup_retention_period = 14 -> 0, in the middle of dozens of tag changes.

That's what drift looks like on a small team. Nothing dramatic. Security and ops fixes go in through the console or the AWS CLI first, because that is faster on the day, and the code quietly goes stale.

In this blog we will look at how I reconcile that: list what changed live, change the code to match the account (not the other way round), and only trust a plan that deletes nothing.

How the account got ahead

Our infra repo was reverse-engineered from a live account. When we did a full reconciliation on 25 September 2026, this is roughly what had landed outside Terraform since the code was written:

  • the test environment's bastion was closed: 0.0.0.0/0 on two ports replaced with one /32 per operator;
  • the move of service credentials into Secrets Manager was deployed for most services, plus two new secrets;
  • a DNS zone cutover finished;
  • an IAM policy was patched live, twice (the RequireMFA story is the reason);
  • an unused VPC was deleted;
  • the production bastion's operator list had grown well past what the repo had;
  • and the backup retention, 0 in code and 14 live.

None of these were mistakes. Every one was the right fix done the quick way. The mistake would have been to treat the repo as the truth after that.

Rule one: code follows the account

When the two disagree, the question is "which one is right?", and nine times out of ten the live one is right, because someone changed it for a reason. So I change the HCL to match. The reverse, applying the file to "fix" the account, undoes a security fix or, like here, a backup setting.

For RDS, the reconciled block now carries the reason with it (trimmed here, with placeholder names):

resource "aws_db_instance" "backend" {
  identifier     = "my-db"
  engine         = "postgres"
  engine_version = "17.6"
  instance_class = "db.t4g.medium"

  allocated_storage           = 50
  username                    = "app"
  manage_master_user_password = true

  # Reconciled to the live value. Backups were turned on in the console and
  # the instance keeps 14 days; this file used to say 0.
  backup_retention_period = 14
  deletion_protection     = true
  skip_final_snapshot     = true
}

The comment is half the fix. Next person who sees 14 and wonders whether it's a typo gets the answer right there.

Listing what changed

If the root has state, Terraform will tell you. terraform plan -refresh-only compares state with the real account and shows only the differences, without proposing any change to infrastructure. Read it; don't apply it until the code is fixed, because applying it just writes the live values into state.

Our roots had no state at all. The import blocks were committed but commented out, the adoption was still pending. So I went resource by resource with the CLI. A few that were useful:

aws rds describe-db-instances --db-instance-identifier my-db \
  --query 'DBInstances[0].[BackupRetentionPeriod,DeletionProtection,MultiAZ]'

aws ec2 describe-security-groups --group-ids sg-0123456789abcdef0 \
  --query 'SecurityGroups[0].IpPermissions[].[FromPort,IpRanges[].CidrIp]'

aws iam get-policy --policy-arn arn:aws:iam::111122223333:policy/RequireMFA \
  --query 'Policy.DefaultVersionId'

For IAM policies I don't eyeball. I fetch the default version's document and diff it with the JSON the code renders, both sorted by jq -S. Here the code's policy is a plain file; ours is built in HCL, so we rendered it first:

aws iam get-policy-version \
  --policy-arn arn:aws:iam::111122223333:policy/RequireMFA \
  --version-id v3 --query 'PolicyVersion.Document' --output json | jq -S . > live.json
jq -S . policies/require-mfa.json > code.json
diff live.json code.json && echo "same"

That's how we confirmed the committed policy matched the live v3 exactly, so importing it later would be a no-op. An empty diff is the best feeling in this whole exercise, honestly.

CloudTrail helps when you have doubts about what changed. Event history keeps 90 days of management events, so filtering by a resource name usually tells you who changed it and when. That's often more useful than the value itself.

The roots with no state

This is the uncomfortable middle. Code exists, resources exist, state doesn't. A plain plan wants to create everything, and an apply fails on the first resource that already exists. For IAM that looks like EntityAlreadyExists, which is at least loud.

The way out is import blocks (I covered them in importing hand-built AWS resources into Terraform):

import {
  to = aws_db_instance.backend
  id = "my-db"
}

With the stage-one imports uncommented, our three roots planned against the live account with 0 to destroy in each. The changes were almost all tag additions from default_tags. That number, 0 to destroy, is the one I care about. Changes you can read. Destroys on a root that holds a production database, you can't take back.

Until the imports are applied, the drift stays, and I think that's fine as long as it's written down. We keep a "recent live changes" table in the architecture docs, so whoever runs the adoption next knows the account is ahead of the repo in those exact places, on purpose.

A plan that deletes is a stop sign

I don't trust myself to spot one delete in a long plan, so a small script does it:

#!/usr/bin/env bash
# Refuse to apply a plan that deletes or replaces anything.
set -euo pipefail

terraform plan -input=false -out=tfplan >/dev/null
terraform show -json tfplan > tfplan.json

risky=$(jq -r '
  .resource_changes[]
  | select(.change.actions | index("delete"))
  | "\(.change.actions | join("+"))  \(.address)"
' tfplan.json)

if [[ -n "$risky" ]]; then
  echo "Plan deletes or replaces:"
  echo "$risky"
  exit 1
fi

jq -r '
  .resource_changes[]
  | select(.change.actions != ["no-op"] and .change.actions != ["read"])
  | "\(.change.actions | join("+"))  \(.address)"
' tfplan.json
echo "No deletes. Read the changes above before you apply."

A replace shows up as delete plus create in the JSON, so the same check catches "forces replacement" too. I tested the two jq filters against a hand-written plan JSON with an update, a replace and a no-op; the replace was flagged and the no-op skipped. It does not catch the retention problem, by the way. 14 -> 0 is an update. For that you still have to read the plan, which is the whole point of printing the changes at the end.

The wrong account

One more guard, because it nearly matters more than all of the above. The laptop I work on has a default AWS profile pointing at a completely different account. A bare terraform plan there would happily compare our code against the wrong account and propose creating everything. So every root pins both:

provider "aws" {
  region              = "ap-south-1"
  profile             = var.aws_profile
  allowed_account_ids = [var.account_id]
}

With allowed_account_ids, the provider refuses to run if the credentials belong to any other account. It fails loudly before reading anything. I'd put this in every root, even single-account setups; it costs one line.

When the CLI is the right tool anyway

Some changes will keep going through the CLI, and that's okay. We change ECS task definitions with the AWS CLI on purpose: copy the live revision, edit it, register-task-definition, update-service. CI deploys copy the latest revision of the family, so a CLI change carries forward on its own. In Terraform the service module has ignore_changes = [task_definition, desired_count], so the code owns the shape of the service and CI owns the revision. Two owners basically, but for different fields, which is fine. Drift is only a problem when nobody wrote down who owns what.

If your plans run in CI (plan on pull request, apply on merge), put the delete check in that job and make it a required check.