Skip to content

InsightsAutomation

Scheduled Terraform drift detection that someone acts on

How to run terraform plan on a schedule with -detailed-exitcode, tell real drift from unapplied changes, route findings to the owning team, and decide for each finding whether to revert the infrastructure or update the code.

Published October 31, 20267 min read

Terraform describes what should exist, and for a while it does. Then someone widens a security group during an incident, an autoscaling setting is changed in the console, or a tag is rewritten by another tool. Nothing fails. The next person to run terraform plan finds an unrelated change in the output, and either reverts it without knowing why it was made or learns to ignore the noise.

The fix is to run the plan yourself, on a schedule, before anyone needs it. This article covers the plan flags that make that scriptable, a workflow that reports instead of applying, how to separate drift from unfinished work, and what to do with each finding.

What drift is, and what Terraform can see

Every terraform plan refreshes first: it reads the real objects and compares them with state. The plan output then opens with "Objects have changed outside of Terraform" and lists what moved since the last apply, followed by the changes needed to bring the objects back in line with the configuration.

Terraform can only see what it manages and what the provider reads back. It will not find a resource created by hand and never imported, and it cannot compare attributes the provider does not return. Secrets passed as write-only arguments have no stored value to compare (see keeping secrets out of state). Drift detection covers the managed surface, which is still the part that causes surprises.

The two flags that matter

terraform plan has two options that turn it into a check:

FlagEffectUse it for
-detailed-exitcodeExit code 0 for an empty diff, 1 for an error, 2 for a non-empty diffTelling "clean", "broken" and "differs" apart in a script
-refresh-onlyPlans only an update of state and root outputs, and proposes no changes to infrastructureReviewing drift on its own, and accepting it into state with terraform apply -refresh-only

Without -detailed-exitcode, a plan exits 0 whether or not it found changes, so a scheduled job would always look green. Also use -input=false so a missing variable fails the job instead of waiting for a prompt, and -no-color for readable logs. Avoid -lock=false: it saves a few seconds and risks reading state in the middle of someone's apply.

A plain plan with -detailed-exitcode reports two different things under the same exit code 2:

  • Drift: the real object differs from state.
  • Unapplied configuration: the code on the branch differs from state because a merged change has not been applied yet.

Run the check against the branch you deploy from, and only when no apply is queued, or the second kind will fill your reports with changes that are about to land anyway.

A workflow that reports and never applies

The job below checks one stack on a schedule and opens or updates an issue when the plan is not clean. It has no apply step and uses credentials that can read the infrastructure and state but cannot change either.

.github/workflows/drift.yml
name: Drift detection
 
on:
  schedule:
    - cron: "17 5 * * *"
  workflow_dispatch:
 
permissions:
  id-token: write
  contents: read
  issues: write
 
jobs:
  plan:
    runs-on: ubuntu-latest
    strategy:
      fail-fast: false
      matrix:
        stack: [network, platform, data]
    steps:
      - uses: actions/checkout@v4
        with:
          ref: main
      - uses: hashicorp/setup-terraform@v3
        with:
          terraform_wrapper: false
      - uses: aws-actions/configure-aws-credentials@v4
        with:
          role-to-assume: arn:aws:iam::111122223333:role/terraform-drift-readonly
          aws-region: eu-west-1
      - name: Plan
        working-directory: stacks/${{ matrix.stack }}
        run: |
          terraform init -input=false
          code=0
          terraform plan -detailed-exitcode -input=false -no-color -lock-timeout=5m \
            -out=plan.bin > plan.txt || code=$?
          echo "code=$code" >> "$GITHUB_ENV"
          [ "$code" -ne 1 ] || { cat plan.txt; exit 1; }
      - name: Report
        if: env.code == '2'
        env:
          GH_TOKEN: ${{ github.token }}
        run: |
          gh issue create --title "Terraform drift: ${{ matrix.stack }}" \
            --label drift --body-file stacks/${{ matrix.stack }}/plan.txt

A few choices in it are deliberate:

  • terraform_wrapper: false. The default wrapper in hashicorp/setup-terraform captures output and exit code for later steps. Here the shell captures the exit code itself, which keeps the behavior visible in the workflow file.
  • || code=$?. GitHub runs run steps with bash -e, so a plain exit code 2 would fail the step. Capturing the code lets the job tell an error (1) from a finding (2).
  • One matrix entry per stack, with fail-fast: false. One broken stack should not hide the state of the others. Managing many accounts covers generating this matrix from a directory listing.
  • Short-lived read-only credentials. Use OIDC federation to a role that can read resources and state, nothing more. A drift job that can apply is an unattended deployment pipeline.

The issue body is the plan text. Plan output can contain values you would not paste into a ticket: sensitive values are masked, but a resource attribute that happens to hold something private is not always marked. Check what your plans print before posting them where more people can read them, or link to the workflow run instead of copying the text. The saved plan.bin is worse: the Terraform documentation notes that sensitive values are stored in it in cleartext, so do not upload it as an artifact on a repository others can read.

Dealing with noise

The first scheduled run on a mature stack usually reports a dozen diffs. Most are not drift anyone cares about. Sort them before you alert on them:

  1. Provider-computed attributes that flip between runs. Fix the configuration with lifecycle { ignore_changes = [...] } on the specific attribute, with a comment saying who else writes it. Do not ignore a whole resource.
  2. Attributes owned by another system. An autoscaler that changes desired_capacity, a controller that adds tags. Declare the split: ignore the attribute in Terraform and let the other system own it.
  3. Provider upgrades that change defaults. These appear on every stack at once after a version bump. Review them as part of the upgrade, not as drift.
  4. Real out-of-band changes. These are what you came for.

Spend a week cleaning categories one to three. A check that is red every day trains people to stop looking at it, and the reports that matter then look the same as the ones that do not.

What to do with a finding

Each real finding needs a decision, and the person who made the change should be part of it. There are only two outcomes.

Revert the infrastructure. The change was a mistake, an experiment or an emergency fix that outlived the emergency. Run a normal apply through your usual pipeline, which restores what the code says. Check the plan first: reverting a security group rule can cut off whatever started depending on it.

Accept it into the code. The change was right, and the code is behind. Edit the configuration to match, then run terraform plan -refresh-only to confirm that the remaining difference is only state. Accept it with terraform apply -refresh-only, which, as its confirmation prompt says, writes the changes to state without modifying any real infrastructure. Skipping the code edit is the common mistake: the state then agrees with the console, the configuration does not, and the next normal apply reverts the change.

In both cases, record why. A short comment in the pull request or the drift issue is enough, and it is the part that stops the same console edit from happening again next month.

Routing and ownership

A drift issue in a shared tracker belongs to nobody. Attach each stack to an owner and send the report there:

  • Put the owning team in a CODEOWNERS entry or a small stacks.yaml, and have the workflow read it when it assigns the issue or posts to the team's channel.
  • Reuse one issue per stack: look for an open issue with the drift label and the stack name, and comment on it instead of creating a duplicate each night. Close it automatically when a later run exits 0.
  • Send a finding to a chat channel only if someone is expected to act within the day. Everything else belongs in a ticket with a due date.

The same stack list can feed a simple dashboard: the number of stacks clean, drifted and failing, and the age of the oldest open finding. The age is the number to watch, because it shows whether findings are being handled or only reported.

Limits worth knowing

  • Plans cost API calls. Each plan reads every managed object. On large stacks, nightly runs can hit provider rate limits or take long enough to overlap with a deployment. Split big stacks, stagger the schedule and use -lock-timeout so a run that meets an active apply waits briefly and then fails visibly.
  • State access is part of the permission set. The read-only role still needs to read the state backend, and reading state exposes any sensitive values in it. Scope that access as carefully as write access.
  • Detection is not prevention. Daily checks tell you a day later. To limit who can change things in the first place, combine this with narrower console permissions and policy checks on plans.
  • Scheduled workflows are not exact. GitHub can delay a scheduled run during busy periods, and it pauses scheduled workflows in repositories with no activity for 60 days. Alert on a drift check that has not run, as you would for any other scheduled job.

Where to start

  1. Pick the stack that has caused the most surprise applies and run terraform plan -detailed-exitcode on it by hand.
  2. Sort the output into the four categories above and fix the first three.
  3. Add the scheduled workflow with read-only credentials, no apply step and one issue per stack.
  4. Assign an owner to every stack and agree on the revert or accept rule.
  5. Extend to the remaining stacks one at a time, and track the age of the oldest open finding.