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:
- Desired State (Configuration): Your Terraform configuration files (
.tffiles) define the desired state of your infrastructure. For example, they declare that you want a specific file to exist with certain content. - Expected State (State File): After you run
terraform apply, Terraform records the details of the resources it created (like theid,filename,content, etc., for ourlocal_file) in itsterraform.tfstatefile. This is Terraform's current understanding of the infrastructure it manages. - Actual State (Real-world Infrastructure): When you run commands like
terraform plan,terraform apply, orterraform refresh, Terraform makes API calls (or performs local checks for resources likelocal_file) to the cloud provider or your system to inspect the current, real-world status of those resources. - Comparison and Drift Detection: Terraform then compares the
expected state(from its state file) with theactual state(from its inspection).- If there's a discrepancy (e.g., the state file says
example.txtexists, 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.
- If there's a discrepancy (e.g., the state file says
In our current step, when you ran rm example.txt, you created a drift.
- Before
rm: Terraform's state file saidlocal_file.example_renamedexisted at./example.txt. - After
rm:local_file.example_renamedno longer existed on the file system. - When you ran
terraform plan(orrefresh): Terraform checked the file system, saw that./example.txtwas gone, compared it to its state file, and detected the drift. It then proposed tocreatethe 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?