Terraform
Basics & Fundamentals
- Infrastructure as Code (IaC)
- Declarative Syntax in IaC
- Terraform Configuration Files
- Terraform CLI
- Terraform Init
- Terraform Plan
- Terraform Apply
- Terraform Destroy
Providers & Resources
Variables & Outputs
- Input Variables
- Variable Types
- Default Values
- Environment Variables
- Output Values
- Variable Validation
State Management
- Terraform State File
- Terraform Remote State
- Terraform State Locking
- Terraform Drift Detection
- Terraform Refresh
- Terraform Import
Modules (Reusability)
- Terraform Modules
- Terraform Public Modules
- Terraform local modules
- Terraform Module Versioning
- Terraform Nested Modules
Provisioners & Lifecycle
🌍 Terraform Drift Detection: Identifying Manual Infrastructure Changes Made Outside Terraform
You’ve built a clean, automated, Infrastructure-as-Code (IaC) setup using Terraform.
Everything is defined in .tf
files — perfect, predictable, and version-controlled.
Then one day, someone in your team logs into the AWS console and manually changes the instance type of an EC2 server.
Terraform doesn’t immediately know this has happened.
This inconsistency between what Terraform thinks exists (state file) and what actually exists in the cloud is called state drift.
And Terraform Drift Detection is how we identify these changes.
🧱 2. What Is Terraform Drift?
Definition:
Terraform Drift occurs when the real-world infrastructure differs from the configuration stored in Terraform’s state file — usually because of manual changes or external automation.
For example:
- An engineer changes a VM size from
t2.micro
tot2.medium
manually. - Someone deletes a security group directly from the console.
- A script outside Terraform modifies tags or IAM roles.
Terraform itself doesn’t continuously monitor these changes. You must detect drift using specific Terraform commands.
⚙️ 3. What Is Drift Detection?
Definition:
Drift Detection in Terraform is the process of comparing the actual infrastructure with the Terraform state to identify any differences or “drift.”
When you run terraform plan
or terraform refresh
, Terraform checks live infrastructure and highlights mismatches between:
- The desired configuration (what’s in your
.tf
files), and - The actual resources (what’s deployed in your cloud).
🔎 4. How Terraform Detects Drift
When you run:
terraform plan
Terraform performs three key actions:
- Reads your configuration files.
- Fetches the current state from the cloud provider (AWS, Azure, GCP, etc.).
- Compares the actual state to the desired configuration.
If differences exist, Terraform reports changes it would make to bring your infrastructure back to the desired state.
🧩 5. Common Causes of Drift
Cause | Example |
---|---|
Manual console changes | Editing instance type or tags in AWS Console |
External automation | A CI job deletes an S3 bucket |
Cloud auto-scaling events | Autoscaler changes the instance count |
Cloud updates | Provider-level changes like new default settings |
Missing state updates | State not refreshed after failed deploy |
🧠 6. Why Drift Detection Matters
Drift might seem harmless — but in real DevOps teams, it’s one of the leading causes of infrastructure instability.
Here’s why it’s crucial:
🔹 1. Prevents Configuration Conflicts
Manual changes can break future Terraform runs. Drift detection ensures your next terraform apply
doesn’t undo or overwrite changes unexpectedly.
🔹 2. Ensures Infrastructure Consistency
In large environments, Terraform is the “single source of truth.” Drift detection keeps it that way.
🔹 3. Detects Unauthorized Changes
Drift reports reveal if someone made unauthorized modifications outside the approved IaC process.
🔹 4. Supports Compliance and Auditing
Drift detection helps maintain compliance with change management policies — especially in regulated industries.
☁️ 7. Example 1: Drift Detection in AWS
Let’s explore a hands-on example with AWS.
Step 1: Create a Terraform Configuration
provider "aws" { region = "us-east-1"}
resource "aws_instance" "web" { ami = "ami-0c94855ba95c71c99" instance_type = "t2.micro" tags = { Name = "WebServer" }}
Step 2: Apply Configuration
terraform initterraform apply -auto-approve
Terraform provisions a t2.micro instance.
Step 3: Simulate Drift
Go to the AWS Management Console → EC2 → select your instance → change instance type to t2.small manually.
Step 4: Detect Drift
Run:
terraform plan
Terraform output:
~ resource "aws_instance" "web" { instance_type: "t2.micro" => "t2.small"}
This ~
symbol means Terraform detected a difference.
Terraform now plans to revert the instance back to t2.micro — restoring your desired configuration.
Step 5: Fix Drift
terraform apply
Terraform changes the instance back to t2.micro
.
💡 Key Takeaway:
Terraform doesn’t fix drift automatically. It only reports differences — you must apply the plan to restore consistency.
🔷 8. Example 2: Drift Detection in Google Cloud (GCP)
Step 1: Create a Terraform Configuration
provider "google" { project = "my-gcp-project" region = "us-central1"}
resource "google_compute_instance" "app" { name = "app-server" machine_type = "e2-micro" boot_disk { initialize_params { image = "debian-cloud/debian-11" } } network_interface { network = "default" access_config {} }}
Step 2: Apply the Configuration
terraform initterraform apply -auto-approve
Step 3: Introduce Drift
Manually change the machine type from e2-micro to e2-medium in the Google Cloud Console.
Step 4: Detect Drift
terraform plan
Terraform output:
~ resource "google_compute_instance" "app" { machine_type: "e2-micro" => "e2-medium"}
Step 5: Fix Drift
terraform apply
Terraform reverts it back to e2-micro, restoring your infrastructure’s intended state.
🔹 9. Example 3: Drift Detection in Azure
Step 1: Create Terraform Configuration
provider "azurerm" { features {}}
resource "azurerm_resource_group" "example" { name = "rg-drift-example" location = "East US"}
resource "azurerm_storage_account" "storage" { name = "driftdetectdemo" resource_group_name = azurerm_resource_group.example.name location = azurerm_resource_group.example.location account_tier = "Standard" account_replication_type = "LRS"}
Step 2: Apply Configuration
terraform initterraform apply -auto-approve
Step 3: Introduce Drift
Go to the Azure Portal, open your storage account, and change the replication type from LRS to GRS manually.
Step 4: Detect Drift
terraform plan
Terraform output:
~ resource "azurerm_storage_account" "storage" { account_replication_type: "LRS" => "GRS"}
Step 5: Fix Drift
terraform apply
Terraform updates it back to LRS.
💡 Key Takeaway:
In all three cases, Terraform detects but doesn’t automatically correct drift — this ensures transparency and controlled remediation.
🧰 10. Commands Useful for Drift Detection
Command | Description |
---|---|
terraform plan | Compares current and desired infrastructure state |
terraform refresh | Updates local state to match real resources |
terraform show | Displays current known state |
terraform apply | Reconciles drift by re-applying configuration |
🧠 11. How to Remember the Concept (Drift = “D.I.F.F.”)
Use this simple mnemonic: D.I.F.F.
Letter | Meaning | Explanation |
---|---|---|
D | Detect | Use terraform plan to detect changes |
I | Identify | Pinpoint which resources have drifted |
F | Fix | Apply Terraform configuration to restore state |
F | Future-proof | Use policies and automation to prevent manual edits |
When preparing for interviews, think:
“Drift Detection is about spotting the DIFF between Terraform and reality.”
📘 12. Why It’s Important to Learn Drift Detection
🔹 1. It’s a Real-World Problem
Manual edits happen — whether by mistake or necessity. Knowing how to detect and handle drift makes you a more reliable engineer.
🔹 2. Core to Certification Exams
Terraform Associate exam frequently asks:
“How do you detect and reconcile infrastructure drift?”
🔹 3. Reduces Risk
Regular drift detection ensures your infrastructure stays predictable and compliant with organizational standards.
🔹 4. Enables Continuous Compliance
Paired with CI/CD tools, drift detection can alert you to unauthorized infrastructure changes automatically.
🧩 13. How to Automate Drift Detection
You can automate drift detection using tools like:
- Terraform Cloud – automatic drift detection for workspaces.
- Atlantis / Spacelift – run
terraform plan
periodically and alert on drift. - Custom Cron Jobs – schedule
terraform plan
runs with notifications.
Example: Using Terraform Cloud Drift Detection
Terraform Cloud periodically runs drift detection automatically and sends alerts when differences are found — no manual effort needed.
🧩 14. Example 4: Automated Drift Detection with GitHub Actions
Here’s how to automate drift checks with GitHub Actions:
name: Terraform Drift Detectionon: schedule: - cron: "0 6 * * *" # every day at 6 AMjobs: check-drift: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - uses: hashicorp/setup-terraform@v2 with: terraform_version: 1.8.0 - run: terraform init - run: terraform plan -no-color -detailed-exitcode
Exit code meanings:
- 0 → No drift.
- 2 → Drift detected.
You can use this exit code to trigger Slack or email alerts.
🧠 15. Common Interview Questions
-
What is drift in Terraform? → It’s the difference between actual infrastructure and Terraform’s desired state.
-
How do you detect drift? → Run
terraform plan
orterraform refresh
. -
Does Terraform automatically fix drift? → No, you must apply changes manually with
terraform apply
. -
How do you prevent drift? → Implement IAM restrictions, automation policies, and use drift alerts.
-
What’s the impact of drift in production? → It can cause unpredictable deployments, failed CI/CD runs, or broken dependencies.
🧩 16. Example 5: Using terraform refresh
You can synchronize your local state with actual infrastructure to detect drift:
terraform refreshterraform show
This updates the state file with live data — but doesn’t fix drift automatically.
🧩 17. Example 6: Visualizing Drift
Tools like Infracost, Driftctl, or Terraform Cloud UI can visualize drift graphically.
Example using Driftctl:
driftctl scan --from tfstate://terraform.tfstate --to aws+tf
Output shows which resources are missing, changed, or unmanaged.
🧰 18. Best Practices to Avoid Drift
✅ Restrict console access to prevent manual edits.
✅ Use CI/CD pipelines for all Terraform changes.
✅ Enable drift detection alerts (Terraform Cloud or custom).
✅ Run periodic terraform plan
checks.
✅ Document exceptions (intentional manual changes).
📊 19. Troubleshooting Drift Issues
Problem | Cause | Fix |
---|---|---|
Unexpected plan output | Someone changed resources manually | Revert or re-apply Terraform |
Terraform destroy fails | Resources already deleted manually | Run terraform refresh before destroy |
Sensitive drift | Cloud provider changed default values | Update configuration to match new defaults |
🧠 20. Summary Table
Concept | Description |
---|---|
Definition | Drift detection finds manual or external changes to infrastructure |
Command | terraform plan |
Purpose | Maintain consistency between desired and actual state |
Example Providers | AWS, Azure, GCP |
Memory Trick | D.I.F.F. – Detect, Identify, Fix, Future-proof |
Terraform’s Drift Detection feature is not just a debugging tool — it’s a safeguard for infrastructure integrity.
In the real world, people make manual changes — intentionally or accidentally. Drift detection helps you discover these discrepancies early, keeping your IaC honest and reliable.
Think of it as Terraform’s lie detector — it tells you when your infrastructure isn’t telling the truth.
Mastering drift detection means you understand the full lifecycle of Infrastructure as Code — not just deployment, but monitoring, correction, and prevention.
For any Terraform practitioner, engineer, or certification aspirant — drift detection is a must-learn concept that separates good DevOps engineers from great ones.