How to Detect State Drift in Terraform: Simple Steps
You can detect state drift in Terraform by running
terraform plan. This command compares the real infrastructure with the saved state and shows any differences, helping you spot drift.Syntax
The main command to detect state drift is terraform plan. It compares your current infrastructure with the Terraform state file.
terraform plan: Shows what changes Terraform will make to match your configuration.-refresh=true(default): Updates the state with real infrastructure data before planning.-out=planfile: Saves the plan to a file for review or later apply.
bash
terraform plan
Example
This example shows how to detect drift by running terraform plan after manually changing a resource outside Terraform.
bash
terraform init # Assume a resource like an AWS EC2 instance is created # Manually change the instance type in AWS console terraform plan
Output
An execution plan has been generated and is shown below.
Resource actions are indicated with the following symbols:
~ update in-place
Terraform will perform the following actions:
# aws_instance.example will be updated in-place
~ resource "aws_instance" "example" {
~ instance_type = "t2.micro" -> "t2.small"
}
Plan: 0 to add, 1 to change, 0 to destroy.
Common Pitfalls
Common mistakes when detecting drift include:
- Not running
terraform refreshorterraform planbefore apply, so drift is missed. - Ignoring drift warnings and applying without review.
- Manually editing the state file, which can cause inconsistencies.
- Not using version control for Terraform files, making it hard to track changes.
Always use terraform plan to review changes before applying.
bash
terraform apply # without plan
# This can apply unexpected changes if drift exists
# Correct approach:
terraform plan
terraform applyQuick Reference
Tips to detect and manage state drift:
- Run
terraform planregularly to check for drift. - Use
terraform refreshto update state from real resources. - Review plan output carefully before applying.
- Use version control to track configuration changes.
- Avoid manual changes outside Terraform to reduce drift.
Key Takeaways
Run
terraform plan to detect state drift by comparing real infrastructure with Terraform state.Always review the plan output before applying changes to avoid unexpected updates.
Avoid manual changes outside Terraform to minimize drift.
Use
terraform refresh to update state with real resource data when needed.Keep Terraform configurations in version control for better change tracking.