Skip to main content

Detecting and Fixing Terraform Drift

Detect Terraform drift with plan and refresh-only, automate daily checks in CI, and decide whether to revert or codify console changes in AWS.

26 Terms

Overview and What You Will Learn

Terraform drift is the gap between what your configuration and state say is deployed and what actually exists in the cloud, usually caused by a manual change made outside Terraform. You find it by running terraform plan, which refreshes real infrastructure before comparing, and you fix it either by applying to revert the change or by updating your code to keep it.

Picture an engineer who logs into the AWS console at 2am during an incident and changes a health check path to stop the bleeding. The fix works and the incident closes, but Terraform still believes the old value is deployed. That gap quietly grows until nobody trusts terraform plan output because it is full of changes nobody asked for.

By the end of this topic you will be able to:

  • Explain how and why drift happens, using real incident-response scenarios
  • Use terraform plan and terraform plan -refresh-only to detect drift
  • Choose between reverting drift and codifying it in your .tf files
  • Schedule automated drift detection in GitHub Actions with a read-only role
  • Find resources that were never under Terraform management
  • Reduce drift at the source with tags and IAM deny policies
  • Follow a clear incident procedure the next time drift appears in production

Why This Matters in Production

Unreconciled drift turns a routine pull request into a production risk. Imagine a team at a company like Hotstar where an on-call engineer changes an ALB target group health check path in the console during a cricket match. Three weeks later, an unrelated pull request shows a change to that same path with no explanation in the diff, and the reviewer almost approves it as harmless. That approval would have reverted a deliberate, still-needed fix right before the next big match.

Drift is also a trust problem. When your team stops believing terraform plan, you have lost the main safety net in your infrastructure workflow.

Core Principles

Drift is not a bug in your Terraform code. Your code can be perfectly correct while reality has moved because someone changed it outside Terraform. Every terraform plan refreshes real infrastructure first, so every plan is also a drift check.

flowchart TD A([Manual change in console]) --> B[Real infra differs from state] B --> C[terraform plan detects drift] C --> D[Keep the change or revert it?] D -->|Revert| E[terraform apply
restores the .tf config] D -->|Keep| F[Update .tf, open PR,
then apply] E --> G[Code, state, and cloud match] F --> G classDef alert fill:#EF4444,color:#FFFFFF classDef warn fill:#F97316,color:#FFFFFF classDef tool fill:#326CE5,color:#FFFFFF classDef decide fill:#F59E0B,color:#111827 classDef good fill:#D1FAE5,color:#1E293B class A alert class B warn class C tool class D decide class E,F,G good
Remember

terraform plan only compares resources that already exist in state. A resource someone created by hand and never imported is invisible to it, which is why the unmanaged-resource audit later in this lab matters.

Detailed Step-by-Step Practical Lab

This lab uses a tiny S3 bucket so you can create drift safely and cheaply. You need Terraform 1.5 or later, the AWS CLI, and credentials for a sandbox account.

How to Create a Resource and Cause Drift on Purpose

Create a bucket with a tag set that Terraform owns:

Bash
mkdir drift-lab && cd drift-lab
cat > main.tf << 'EOF'
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 6.0"
}
}
}
provider "aws" {
region = "ap-south-1"
}
resource "aws_s3_bucket" "lab" {
bucket = "drift-lab-rahul-2026"
tags = {
ManagedBy = "terraform"
Owner = "platform-team"
}
}
EOF
terraform init
terraform apply -auto-approve

Now simulate the 2am console change by editing the tags outside Terraform:

Bash
aws s3api put-bucket-tagging \
--bucket drift-lab-rahul-2026 \
--tagging 'TagSet=[{Key=ManagedBy,Value=terraform},{Key=Owner,Value=oncall-rahul}]'
How to Detect Drift with terraform plan

Run a normal plan. Terraform refreshes the bucket first and reports what changed outside its control:

Bash
terraform plan

The output has two parts, and the drift part appears first:

Bash
Note: Objects have changed outside of Terraform
Terraform detected the following changes made outside of Terraform since the
last "terraform apply" which may have affected this plan:
# aws_s3_bucket.lab has changed
~ resource "aws_s3_bucket" "lab" {
~ tags = {
~ "Owner" = "platform-team" -> "oncall-rahul"
}
}
Unless you have made equivalent changes to your configuration, or ignored the
relevant attributes using ignore_changes, the following plan may include
actions to undo or respond to these changes.
Tip

Read every plan from top to bottom before approving. Engineers who skim often miss the drift section, which sits above the planned changes.

How to Check for Drift Only with refresh-only

A plain plan mixes drift with pending code changes. To isolate drift, ask Terraform only what would change in state:

Bash
terraform plan -refresh-only

This shows the same drift but ignores your configuration, so it answers one question: has reality moved? It is the cleanest signal for scheduled checks.

How to Keep a Manual Change (Codify Drift)

If the manual change was correct, accept it into state and then update the code to match. The -refresh-only apply reads real infrastructure and updates only the state file. It does not change any real resource:

Bash
terraform apply -refresh-only
# Answer yes. Result: Apply complete! Resources: 0 added, 0 changed, 0 destroyed.

Now edit main.tf so the code matches reality, then confirm the plan is clean:

Bash
sed -i 's/Owner = "platform-team"/Owner = "oncall-rahul"/' main.tf
terraform plan
# No changes. Your infrastructure matches the configuration.
Security

A -refresh-only apply without a matching .tf change leaves your code lying about the deployed state. The next plan shows the same drift again, and the next engineer reads the wrong config. Always follow it with a pull request.

How to Revert a Manual Change (Reconcile Drift)

If the manual change was a temporary emergency fix you do not want to keep, apply your configuration. Terraform puts the real resource back. To try it, drift the tag again and then apply:

Bash
aws s3api put-bucket-tagging \
--bucket drift-lab-rahul-2026 \
--tagging 'TagSet=[{Key=ManagedBy,Value=terraform},{Key=Owner,Value=someone-else}]'
terraform plan
terraform apply -auto-approve
# aws_s3_bucket.lab: Modifying...
# Apply complete! Resources: 0 added, 1 changed, 0 destroyed.
How to Automate Scheduled Drift Detection in CI

Do not wait for an unrelated pull request to stumble onto drift. Run a scheduled read-only check against production every day. This workflow uses -refresh-only with -detailed-exitcode, which returns 0 for no drift, 1 for an error, and 2 when drift exists:

YAML
# .github/workflows/drift-detection.yml
name: Scheduled Drift Detection
on:
schedule:
- cron: "0 6 * * *" # every day at 6am UTC
workflow_dispatch: # allow manual runs
jobs:
detect-drift:
runs-on: ubuntu-latest
environment: production
permissions:
id-token: write # required for OIDC
contents: read
steps:
- uses: actions/checkout@v4
- uses: hashicorp/setup-terraform@v3
with:
terraform_version: "1.9.0"
- name: Configure AWS credentials via OIDC
uses: aws-actions/configure-aws-credentials@v4
with:
role-to-assume: arn:aws:iam::123456789012:role/terraform-drift-readonly
aws-region: ap-south-1
- name: Terraform Init
run: terraform init -input=false
working-directory: environments/prod
- name: Detect Drift
id: drift
working-directory: environments/prod
run: |
set +e
# -lock=false keeps this job read-only, so it never needs state-lock write access
terraform plan -refresh-only -detailed-exitcode -no-color -input=false -lock=false > plan_output.txt 2>&1
code=$?
echo "exitcode=$code" >> "$GITHUB_OUTPUT"
cat plan_output.txt
if [ "$code" -eq 1 ]; then exit 1; fi
- name: Alert on Drift
if: steps.drift.outputs.exitcode == '2'
env:
SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK_URL }}
RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}
run: |
curl -s -X POST "$SLACK_WEBHOOK_URL" \
-H 'Content-type: application/json' \
--data "{\"text\": \":rotating_light: Drift detected in prod. Details: $RUN_URL\"}"
- name: Fail job when drift is found
if: steps.drift.outputs.exitcode == '2'
run: exit 1 # turns the scheduled run red in the GitHub UI
Tip

Give the drift job its own IAM role with read-only access to the resources and the state bucket, not the apply role. If those CI credentials ever leak, the blast radius is read access only.

How to Find Resources Terraform Does Not Manage

Plan and refresh-only checks cover only resources already in state. To find things created by hand, audit for resources missing your management tag. This rough check lists EC2 instances that lack a ManagedBy tag:

Bash
aws ec2 describe-instances \
--region ap-south-1 \
--query "Reservations[].Instances[?!Tags[?Key=='ManagedBy']].InstanceId" \
--output text

When you find a useful unmanaged resource, bring it under Terraform with an import block (Terraform 1.5 and later) and let Terraform draft the configuration for you:

Bash
cat > import.tf << 'EOF'
import {
to = aws_instance.legacy_bastion
id = "i-0abc123def4567890"
}
EOF
terraform plan -generate-config-out=generated.tf

Review generated.tf, move it into your real files, then apply. For broader coverage across many resource types, use AWS Config or a drift feature in your Terraform platform, such as HCP Terraform health assessments.

Common Mistake

Reaching for Driftctl because older guides recommend it. The Snyk Driftctl project is in maintenance mode and its repository notes it no longer accepts active development, and users report problems with state from newer providers. Check a tool's maintenance status before building a workflow around it.

How to Prevent Drift with Tags and IAM Policies

Tag every Terraform-managed resource, then deny manual changes to tagged resources for everyone except your pipeline and a break-glass role:

HCL
locals {
common_tags = {
ManagedBy = "terraform" # drives the IAM deny policy below
Environment = var.environment # prod, staging, dev
Project = "payment-api"
Team = "platform-engineering"
}
}
resource "aws_instance" "app_server" {
ami = data.aws_ami.ubuntu.id
instance_type = "t3.medium"
tags = local.common_tags
}
resource "aws_iam_policy" "deny_manual_changes" {
name = "deny-manual-changes-to-terraform-resources"
policy = jsonencode({
Version = "2012-10-17"
Statement = [{
Sid = "DenyManualChangesToTerraformResources"
Effect = "Deny"
Action = [
"ec2:ModifyInstanceAttribute",
"ec2:AuthorizeSecurityGroupIngress",
"ec2:RevokeSecurityGroupIngress",
"rds:ModifyDBInstance"
]
Resource = "*"
Condition = {
StringEquals = {
"aws:ResourceTag/ManagedBy" = "terraform"
}
ArnNotLike = {
"aws:PrincipalArn" = [
"arn:aws:iam::123456789012:role/github-actions-terraform",
"arn:aws:iam::123456789012:role/break-glass-oncall"
]
}
}
}]
})
}

Attach this policy to your engineer groups or apply it as a Service Control Policy. The break-glass role is deliberate: during a real outage, restoring service comes before Terraform purity, and the deny policy should not block the person fixing production.

What to Do When Drift Appears in Production

Follow these steps every time drift is found, whether from a scheduled alert or a confusing pull request plan:

  1. Identify. Run terraform plan -refresh-only and note which resources drifted and what changed.
  2. Trace. Find who changed it and when in CloudTrail. Event history covers the last 90 days of management events:
Bash
aws cloudtrail lookup-events \
--lookup-attributes AttributeKey=ResourceName,AttributeValue=sg-0abc123 \
--start-time 2026-10-01T00:00:00Z \
--region ap-south-1
  1. Decide. If the change was intentional and correct, update the .tf file, open a pull request, and apply. If it was wrong or temporary, run terraform apply to revert it.
  2. Document. Post in the incident channel what drifted, why it was changed, what you did, and the pull request link.
  3. Prevent. If an IAM gap or a broken runbook caused it, fix that too.
Remember

During an active incident, stop the incident first and keep Terraform consistent second. Make the manual fix, then run this procedure once service is restored.

Clean up the lab:

Bash
terraform destroy -auto-approve
cd .. && rm -rf drift-lab

Production Best Practices & Common Pitfalls

Common Mistake

Treating -refresh-only as the whole job. Updating state without updating the .tf file means the next plan shows the same drift again and your code no longer describes reality.

Tip

Combine prevention with detection. IAM policies stop most console drift, and scheduled checks catch the rest, including break-glass changes and changes made by other teams' automation.

  • Never let drift sit for more than one sprint. The longer a manual change goes unreconciled, the more likely someone reverts it accidentally or builds on top of it.
  • Run detection on a schedule, not once. A one-time check shows only today's problem, and unmanaged resources accumulate silently over months.
  • Use ignore_changes for attributes that legitimately self-modify. Auto Scaling groups adjust desired_capacity, and automation can rotate AMIs. These show up as drift on every plan until you tell Terraform they are managed elsewhere:
HCL
resource "aws_autoscaling_group" "app" {
# ... other config ...
lifecycle {
# desired_capacity is managed by scaling policies, not Terraform
ignore_changes = [desired_capacity]
}
}
  • Keep the drift job read-only. Use a separate role and -lock=false so a scheduled check can never change infrastructure or block a real apply.
  • Alert to a channel people read. A red scheduled job that nobody watches is just drift with extra steps.

Quick Reference & Troubleshooting Commands

Command Description
terraform plan Detect drift and pending code changes together
terraform plan -refresh-only Show drift only, ignoring your configuration
terraform plan -refresh-only -detailed-exitcode Exit code 2 when drift exists, for CI scripts
terraform apply -refresh-only Update state to match reality without changing real resources
terraform apply Revert drift by restoring real infrastructure to your config
terraform plan -generate-config-out=generated.tf Draft configuration for resources in import blocks
terraform plan -refresh=false Skip refresh entirely, faster but cannot detect drift
Symptom Likely cause Fix
Unexplained diff in an unrelated PR A manual change was never reconciled Trace in CloudTrail, then revert or codify
Plan is clean but behavior is wrong The resource was never in state Audit for untagged or unmanaged resources and import them
Drift returns after a refresh-only apply The .tf file was never updated Edit the resource block, not just state
Scheduled job always reports drift An attribute changes naturally, such as desired_capacity Add ignore_changes for that attribute
Drift job fails with a lock error The job tried to take a state lock Add -lock=false and keep the role read-only

Resources

Explore More in Terraform in Production - CI/CD, Secrets, and Governance

All 3 Topics

Frequently Asked Questions

Is Detecting and Fixing Terraform Drift free to learn on DevOps Network?

Yes - this topic, like everything on DevOps Network, is 100% free with no paywall or sign-up gate.

What does the Detecting and Fixing Terraform Drift topic cover?

Detect Terraform drift with plan and refresh-only, automate daily checks in CI, and decide whether to revert or codify console changes in AWS.

Found a mistake, an outdated step or a broken link?