How does Terraform detect drift?

QuestionsQuestions8 SkillsProDec, 16 2025
0155

That's a great question! Terraform detects drift by comparing the expected state (recorded in its state file) with the actual state of your infrastructure.

Here's a more detailed breakdown:

  1. Desired State (Configuration): Your Terraform configuration files (.tf files) define the desired state of your infrastructure. For example, they declare that you want a specific file to exist with certain content.
  2. Expected State (State File): After you run terraform apply, Terraform records the details of the resources it created (like the id, filename, content, etc., for our local_file) in its terraform.tfstate file. This is Terraform's current understanding of the infrastructure it manages.
  3. Actual State (Real-world Infrastructure): When you run commands like terraform plan, terraform apply, or terraform refresh, Terraform makes API calls (or performs local checks for resources like local_file) to the cloud provider or your system to inspect the current, real-world status of those resources.
  4. Comparison and Drift Detection: Terraform then compares the expected state (from its state file) with the actual state (from its inspection).
    • If there's a discrepancy (e.g., the state file says example.txt exists, but the API call reveals it's been deleted), Terraform identifies this as drift.
    • If a property of a resource has changed outside of Terraform (e.g., you manually changed a tag on a server), Terraform will also detect this difference.

In our current step, when you ran rm example.txt, you created a drift.

  • Before rm: Terraform's state file said local_file.example_renamed existed at ./example.txt.
  • After rm: local_file.example_renamed no longer existed on the file system.
  • When you ran terraform plan (or refresh): Terraform checked the file system, saw that ./example.txt was gone, compared it to its state file, and detected the drift. It then proposed to create the file again to bring the real-world infrastructure back into sync with its desired state.

So, in essence, Terraform constantly checks the "truth" of your infrastructure against its internal record to identify any deviations.

Does that explanation clarify how Terraform spots those differences?

0 Comments

no data
Be the first to share your comment!