Tons of new funtionality in Massdriver! We're demoing a new feature everday until Christmas.

Check out the advent calendar here
Engineering
Infrastructure Drift Detection for Terraform and OpenTofu

Infrastructure Drift Detection for Terraform and OpenTofu

How to detect infrastructure drift on a schedule without a pile of cron jobs: why terraform plan in CI gives false positives, what to plan against, and how to alert on drift or fix it with a proposal a person approves.

Cory O'Daniel7 min
Share

Drift is the gap between what your infrastructure as code says and what is actually running in the cloud. Somebody opened a security group in the console during an incident. An autoscaler changed a desired count. A provider upgrade started reporting a default that used to be empty. Another tool tagged every resource in the account. Your code didn't change, and your infrastructure doesn't match it anymore.

I've written before that most drift is a platform design problem. People go around your IaC when your IaC is the slow path. I still believe that. But even a good platform needs a smoke alarm, because the 2 a.m. console fix is going to happen, and you want to hear about it on Tuesday morning, not during the next apply when Terraform tries to undo it.

The usual way: terraform plan on a cron

Nearly every team that does drift detection starts in the same place. A scheduled CI job loops over workspaces and runs:

terraform plan -detailed-exitcode -lock=false

Exit code 0 means no changes, 2 means changes, 1 means something broke. Post to Slack on 2. Done in an afternoon.

Then it runs for a month and you find out what you actually built:

  • It plans the wrong thing. The job checks out main, but main is not what's deployed. A merged-but-unapplied change shows up as drift every night until somebody applies it, and the channel learns to ignore the alert.
  • The variables aren't there. The real apply got its inputs from a tfvars file, a CI secret, and the outputs of three other workspaces. The cron job has to reproduce all of that, for every workspace, or it plans against defaults and reports nonsense.
  • The list of workspaces is maintained by hand. New stacks don't get checked until someone remembers to add them to the matrix.
  • It needs read credentials to everything. Your drift job is now one of the most privileged things in CI.
  • Every result looks the same. Exit code 1 because of an expired token and exit code 2 because of real drift both turn into a red message, and nobody reads past the first line.
  • Fixing it is a separate project. Once you find drift, the next step is "go apply something," which means another pipeline and another person.

Each of these is small. Together they turn the drift channel into the most ignored channel in the company.

Plan the configuration that was deployed

The fix for the first two problems is the same: plan the exact configuration that was last applied, with the exact inputs it was applied with. If the cloud still matches that, there is no drift, regardless of what anybody has merged or saved since.

That's only possible if your system keeps each deployment as a record. Massdriver does. Every PROVISION deployment of an instance stores its bundle version, params, and dependency connections, and planDeployment runs a plan from a deployment. The plan uses that deployment's params, not the instance's saved params, so edits that nobody deployed yet do not show up as drift. It runs on the same pipeline and the same platform-held credentials as every other deployment, so there's no separate drift job with its own keys.

Scheduled drift detection with the drift automation

drift is one of the Massdriver automations. It plans instances on a schedule, reads the plan logs, and alerts Slack when an instance drifted.

The drift-daily drift check runs on a schedule, matches provisioned instances by attribute, plans the last completed PROVISION of each, reads the plan logs, and sorts each plan into drifted, clean, unknown, or failed, with detect, propose, or resolve deciding what happens to a drifted result

A check selects instances by attribute, so you never maintain a list of workspaces. New instances that match driftwatch: drift-daily are in the next run automatically:

slack:
  channel: '#infra-drift'

checks:
  - name: drift-daily
    schedule: '0 6 * * *'
    timezone: America/Los_Angeles
    match:
      driftwatch: drift-daily
      team: [platform, patient-experience, clinical, revenue]
    mode: detect
    resolve_with: deployed
    max_concurrent: 3
    slack:
      channel: '#platform-oncall'
    summary: true

  - name: sandbox-weekly
    schedule: '0 9 * * MON'
    match:
      md-project: sandboxes
    mode: resolve
    resolve_with: saved
    max_concurrent: 2

For each run, the check lists the PROVISIONED instances that match, skips any instance with a deployment that is pending, approved, or running, and plans the latest completed PROVISION of the rest, five at a time by default. The rest wait in a queue.

Each planned instance gets a PLAN deployment from the automation's service account, linked to the deployment it planned. Here, care-dev-charts was planned on the morning after its last provision:

Deployment history of care-dev-charts: a planned deployment by Automations that links Planned deployment of a6241b3024d5, above the provisioned deployment a6241b3024d5 and an earlier plan by Automations

Drifted, clean, unknown, or failed

When the plan finishes, the automation reads its logs. The plan of care-dev-charts found 14 resources whose tags no longer match the configuration:

Plan log of care-dev-charts with tags_all updated in place on a CloudWatch metric alarm and other resources, ending in Plan: 0 to add, 14 to change, 0 to destroy. Signals tab of care-dev-charts: Drift shows Detected, checked 9 hours ago, from deployment c2688b96, and Changes shows drift +0 ~14 -0, next to the steps, worst finding, cost change, and release values

The automation gives each plan exactly one result:

ResultWhen
driftedA plan summary such as Plan: 0 to add, 1 to change, 1 to destroy. counts one or more changes.
cleanEvery step has No changes., or a summary with zero changes.
unknownFewer plan summaries than the bundle has steps, for example when a Helm step prints none.
failedThe plan failed or was aborted, or did not finish within 6 hours.

Drifted, unknown, and failed results go to Slack. The drift alert has the change counts of each step, up to 20 lines of changed resources, and a link to the plan. Clean results stay quiet unless you set notify_clean: true. With summary: true, the check posts one line when the run finishes:

Drift check drift-daily finished: 9 planned, 1 drifted, 8 clean, 0 unknown, 0 failed, 0 skipped.

The drift alert in #platform-oncall: Drift on care-dev-charts (check drift-daily), src: 0 to add, 14 to change, 0 to destroy, the 14 resources that will be updated in place, and a link to plan c2688b96

Keeping "unknown" separate from "drifted" matters more than it looks. A step that the default log patterns can't read is a gap in your coverage, and it should say so instead of hiding inside a red alert or a green one. The default patterns read OpenTofu and Terraform plan output. For other tools, set patterns.clean, patterns.drift, and patterns.resource on the check.

Alert, propose a fix, or fix it now

mode decides what happens to a drifted result:

  • detect (the default) alerts only.
  • propose alerts and creates a deployment that removes the drift, in PROPOSED status, for a person to approve.
  • resolve alerts and deploys the fix right away.

resolve_with decides what the fix applies. deployed (the default) calls rollbackDeployment on the deployment that was planned, which re-applies exactly what was deployed: the same params, bundle version, and dependency snapshot. saved deploys the instance's saved params with its current bundle version, which also ships any edits that nobody deployed yet. The reply in the alert's thread says what the automation did about it: the deployment it created, or why it didn't.

Two guardrails are built in. The automation never resolves an unknown or failed result. And when the instance's resolved bundle version or one of its dependencies changed since the last provision, the plan shows those changes too. The alert names them, and the automation leaves that instance alone, because re-applying would ship more than a drift fix.

My advice: use detect or propose for production. Automatic reconciliation can undo the hotfix that just saved production, and that's exactly the change you most want a person to look at. resolve is great for sandboxes and dev, where "put it back the way the code says" is always the right answer.

Run a check now

A check without a schedule runs only on demand, and any check can run outside its schedule. Set DRIFT_RUN_TOKEN and call:

curl -X POST -H "Authorization: Bearer $DRIFT_RUN_TOKEN" "https://drift.example.com/drift/run?check=drift-daily"

That's handy after an incident, when you want to know right now what someone changed by hand.

Set it up

Deploy the massdriver-drift bundle (Kubernetes) or massdriver-drift-ecs (Amazon ECS with Fargate). The bundle runs the automation and creates its event destination. To run it yourself, create the destination with the mass CLI:

mass event destination create \
  --name drift \
  --url https://drift.example.com/hooks/massdriver \
  --event-type deployment.completed \
  --event-type deployment.failed \
  --event-type deployment.aborted \
  --condition '.data.metadata.deployment_action == "PLAN"'

The service account needs project:view and instance:plan for every mode, plus instance:propose for propose, instance:propose and instance:deploy for resolve with deployed, and instance:deploy for resolve with saved. Mount a STATE_DIR so a restart keeps the plans in progress and the queues, and run one replica, because the schedule lives in one process.

The drift docs have the full config reference. The automations docs cover the rest of the automations, and Run Automations shows how to deploy them.

Stay in the loop