Terraform Plan vs Terraform Refresh — Explained Simply

Listen to this Post

Featured Image
When managing Infrastructure as Code (IaC) with Terraform, state drift is a common challenge. It occurs when the actual infrastructure deviates from what Terraform’s state file expects. This can happen due to manual changes by team members or automatic updates by cloud providers like AWS.

To detect drift, Terraform provides two key commands:

  • terraform plan: Shows the differences between the current state and the desired configuration.
  • terraform refresh: Updates the state file to match the real-world infrastructure without modifying resources.

You Should Know:

1. Detecting Drift with `terraform plan`

Running `terraform plan` compares the state file with the actual infrastructure and highlights discrepancies. Example:

terraform plan 

Output:

~ resource "aws_instance" "example" { 
ami = "ami-0c55b159cbfafe1f0" 
instance_type = "t2.micro" 
} 

2. Syncing State with `terraform refresh`

If you want Terraform to recognize external changes without altering infrastructure, use:

terraform refresh 

This updates the state file to reflect the current state of deployed resources.

3. Forcing State Update (Advanced)

If `refresh` isn’t enough, manually modify the state using:

terraform state rm <resource>  Remove outdated resource 
terraform import <resource> <ID>  Re-import current state 

4. Automating Drift Detection

Add a CI/CD pipeline step to check for drift:

terraform plan -detailed-exitcode 
if [ $? -eq 2 ]; then 
echo "Drift detected!" 
fi 

5. Preventing Drift

  • Use Terraform locks (terraform apply -lock=true).
  • Restrict manual changes via IAM policies in AWS.
  • Implement policy-as-code with Open Policy Agent (OPA).

What Undercode Say:

State drift is inevitable in dynamic cloud environments. While `terraform refresh` helps realign Terraform’s state, always combine it with strict IaC governance. Use:
– `terraform validate` to check syntax.
– `terraform fmt` to standardize configurations.
– `terraform workspace` to manage multiple environments.

For AWS users, monitor drift with:

aws config get-resource-config-history --resource-type AWS::EC2::Instance --resource-id i-1234567890 

In Linux, track changes using:

auditctl -w /path/to/terraform/files -p wa -k terraform_changes 

For Windows, enforce compliance with:

Get-ChildItem -Path C:\terraform.tf | ForEach-Object { Get-FileHash $_ } 

Expected Output:

A well-managed Terraform workflow minimizes drift risks. Use `refresh` cautiously and always back up your state file!

Reference:

References:

Reported By: Darryl Ruggles – Hackers Feeds
Extra Hub: Undercode MoN
Basic Verification: Pass ✅

Join Our Cyber World:

💬 Whatsapp | 💬 Telegram