Skip to content
Tutorials Center
My learning

Topics

Lesson 22 of 37 ยท State Management

Drift Detection, Refresh and Lifecycle Rules

Detect and handle configuration drift in Terraform: refresh-only plans, lifecycle ignore_changes, prevent_destroy and scheduled drift checks for real infrastructure.

Drift is the gap between what Terraform believes exists (its state) and what actually exists. Someone resizes a server in the console during an incident, an autoscaler changes a tag, a teammate opens a security group "just for a minute". Terraform does not see these changes until it looks. This lesson shows how to find drift, decide whether to keep or revert it, and tell Terraform which differences to ignore.

How drift appears

Every plan begins with a refresh, so drift shows up as a diff. Suppose your code says instance_type = "t3.micro" but someone changed it to t3.large by hand. The plan (example output) says:

TEXT
  # aws_instance.web will be updated in-place
  ~ resource "aws_instance" "web" {
      ~ instance_type = "t3.large" -> "t3.micro"
    }

Plan: 0 to add, 1 to change, 0 to destroy.

By default Terraform wants to put reality back to match the code. That is usually right, but sometimes the manual change was an emergency fix you want to keep. You then have two honest choices: update the code to match, or revert the change. The danger is not drift itself; it is not noticing it.

Refresh-only plans

terraform plan -refresh-only reports drift without proposing changes to real infrastructure. It only shows how the state would be updated:

Terminal
terraform plan -refresh-only
terraform apply -refresh-only   # accept: write the new values into state

Accepting a refresh-only apply updates state to match reality; it does not touch your code, so you must edit the code to match, or the next normal plan will revert the change. The old terraform refresh command did the accepting step silently, which is why it was deprecated: you should always see the drift first.

flowchart TD
  A["Scheduled: plan -refresh-only (or plan -detailed-exitcode)"] --> B{"Drift found?"}
  B -->|"No"| Z["Done"]
  B -->|"Yes"| C{"Intended change?"}
  C -->|"Yes"| D["Update code, then apply -refresh-only to sync state"]
  C -->|"No"| E["Normal apply reverts it"]

Decide for every drifted value: keep (change the code) or revert (apply).

Detecting drift automatically

terraform plan -detailed-exitcode returns:

  • 0: no changes
  • 1: error
  • 2: changes present

A nightly CI job can run it against each state and alert on exit code 2. HCP Terraform offers built-in health assessments for the same purpose. The drift detector below is a stand-in that compares a recorded state with the "real" attributes and reports differences with the same exit codes.

Python A tiny drift detector

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Telling Terraform to ignore changes

Some attributes are meant to change outside Terraform: an autoscaling group's desired capacity, tags added by a cost tool, a password rotated by a secrets manager. Use the lifecycle block:

HCL
resource "aws_autoscaling_group" "workers" {
  min_size         = 2
  max_size         = 10
  desired_capacity = 2

  lifecycle {
    ignore_changes = [desired_capacity, tags["last_scanned"]]
  }
}

Terraform still sets the value on creation, but later differences do not appear in the plan. Use ignore_changes = all very rarely: it turns the resource into a write-once object.

Every ignore_changes entry is a hole in your safety net. Write a comment explaining who changes the value and why, and revisit it when that process changes.

Other lifecycle rules

HCL
resource "aws_db_instance" "main" {
  # ...

  lifecycle {
    prevent_destroy       = true   # any plan that destroys it fails
    create_before_destroy = true   # build the replacement first
    replace_triggered_by  = [aws_launch_template.main.latest_version]

    precondition {
      condition     = var.backup_days >= 7
      error_message = "Production databases need at least 7 days of backups."
    }
  }
}
  • prevent_destroy guards stateful resources. It stops terraform destroy too, and it does not apply if you delete the block from the code, so keep reviews strict.
  • create_before_destroy avoids downtime for replacements, but remember names must differ between old and new objects (use name_prefix or random suffixes).
  • replace_triggered_by rebuilds a resource when another one changes.
  • precondition and postcondition blocks check assumptions at plan or apply time.

The stand-in below shows how ignore_changes filters a drift report. It is a model of the behavior, not Terraform's engine.

Python ignore_changes filters the diff

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Reducing drift in the first place

  • Restrict console and CLI write access in production; let the pipeline be the only writer.
  • Tag resources with managed_by = "terraform" so humans notice.
  • Run scheduled drift plans and send exit code 2 to chat or a ticket queue.
  • When an emergency console fix happens, write it down immediately, then codify or revert it within a day.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does terraform plan -refresh-only do?

    It reports drift and what an apply would write into state.
  2. 2. What exit code does plan -detailed-exitcode return when changes exist?

    0 means no changes, 1 means error, 2 means changes (or drift) were found.
  3. 3. Autoscaling changes desired_capacity at runtime. Which setting avoids plan noise?

    ignore_changes tells Terraform not to compare that attribute after creation.
  4. 4. After accepting drift with apply -refresh-only, what must you also do if you want to keep the change?

    Refresh-only changes state, not your .tf files.

Summary

  • Drift is any difference between state and reality; every plan starts by refreshing.
  • Use plan -refresh-only to see drift safely, and -detailed-exitcode for automated checks.
  • Decide per change: update the code to keep it, or apply to revert it.
  • lifecycle rules (ignore_changes, prevent_destroy, create_before_destroy, replace_triggered_by, conditions) tune how Terraform treats a resource.
  • Limit manual changes, and run drift checks on a schedule.

Next: Your First Module