🎓 A1Learner
🔍
0 of 50 lessons completed

Drift: When Reality Changes

Drift is the gap between the state file and the real world. It appears when someone changes a resource outside Terraform.

Change the bucket outside Terraform

This command edits the bucket tags by hand, like a console edit.

aws --endpoint-url http://localhost:5000 s3api put-bucket-tagging --bucket demo-drift --tagging 'TagSet=[{Key=Name,Value=changed-by-hand}]'

Show the drift

The refresh-only plan reports the change and proposes nothing.

terraform plan -refresh-only

Fix the drift

A normal apply writes the configured tags back.

terraform apply -auto-approve

Example

# main.tf
terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 6.0"
    }
  }
}

provider "aws" {
  region = "us-east-1"
  s3_use_path_style = true

  endpoints {
    s3 = "http://localhost:5000"
  }

  skip_credentials_validation = true
  skip_metadata_api_check     = true
  skip_requesting_account_id  = true
}

resource "aws_s3_bucket" "demo" {
  bucket = "demo-drift"

  tags = {
    Name = "demo"
  }
}

# commands (with dummy credentials for the emulator)
export AWS_ACCESS_KEY_ID="test"
export AWS_SECRET_ACCESS_KEY="test"
terraform init
terraform apply -auto-approve
aws --endpoint-url http://localhost:5000 s3api put-bucket-tagging --bucket demo-drift --tagging 'TagSet=[{Key=Name,Value=changed-by-hand}]'
terraform plan -refresh-only
terraform apply -auto-approve
terraform destroy -auto-approve

Key points

  • A console edit, a script, or another tool can change a resource. State still holds the old values.
  • terraform plan -refresh-only shows the drift. It reads reality and reports the gap.
  • A refresh-only plan proposes no changes. It only shows what moved.
  • A normal plan then proposes the fix. It brings reality back to the configuration.
  • Apply writes the fix. The resource matches the configuration again.

The hand edit changed the tags, and the refresh-only plan reported the gap without proposing a fix. The next apply wrote the configured tags back. The final destroy removes the bucket, so nothing is left behind.

Note

the console edit below is faked with the AWS CLI against moto_server, since there is no real console here.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Rust Playground

Exercise

Which command shows drift without proposing changes?