0
0
TerraformConceptBeginner · 3 min read

What Is State Drift in Terraform: Explanation and Examples

In Terraform, state drift happens when the real infrastructure changes outside of Terraform's control, making the state file out of sync with actual resources. This causes Terraform to show differences or unexpected changes when you run commands like terraform plan.
⚙️

How It Works

Think of Terraform's state file as a map that shows what your cloud setup looks like. When you use Terraform to create or change resources, it updates this map to match reality. But if someone changes things directly in the cloud console or with another tool, the map no longer matches the real world. This mismatch is called state drift.

Imagine you have a garden map showing where you planted flowers. If someone moves a flower without telling you, your map is wrong. Terraform notices this difference when you run terraform plan and tells you what changed so you can fix it.

💻

Example

This example shows a simple Terraform configuration for an AWS S3 bucket. If you manually change the bucket's versioning setting in AWS console, Terraform's state drifts from reality.

terraform
provider "aws" {
  region = "us-east-1"
}

resource "aws_s3_bucket" "example" {
  bucket = "my-unique-bucket-12345"
  acl    = "private"
  versioning {
    enabled = false
  }
}
Output
No output on apply, but after manual change: $ terraform plan # aws_s3_bucket.example will be updated in-place ~ resource "aws_s3_bucket" "example" { versioning { enabled = false -> true } }
🎯

When to Use

Understanding state drift is important when multiple people or tools manage the same infrastructure. It helps you detect unexpected changes that can cause problems or outages.

Use Terraform regularly to check for drift, especially after manual changes or automated scripts outside Terraform. This keeps your infrastructure reliable and consistent.

Key Points

  • State drift means real resources changed outside Terraform.
  • Terraform detects drift during terraform plan.
  • Fix drift by updating Terraform code or importing changes.
  • Regular drift checks prevent surprises in infrastructure.

Key Takeaways

State drift occurs when infrastructure changes outside Terraform's control.
Terraform's state file becomes out of sync with actual resources during drift.
Run terraform plan to detect and review drift before applying changes.
Fix drift by updating Terraform code or syncing state with real resources.
Regular drift detection keeps infrastructure stable and predictable.