DEV Community

Cover image for Why terraform apply Broke Production: A Practical Guide to State Drift, Locking, and Safe Recovery
Rahul Sharma
Rahul Sharma

Posted on

Why terraform apply Broke Production: A Practical Guide to State Drift, Locking, and Safe Recovery

Everything looks green in your pull request. ThMastering state management is not just a high-weightage domain on the HashiCorp Certified: Terraform Associate exam—it is the skill that keeps production deployments boring, predictable, and reversible. If you are planning to pair IaC skills with a primary cloud track, this AWS vs. Azure certification comparison guide breaks down how both cloud ecosystems structure their paths and renewal rules.e Terraform configuration has barely changed—just a single tag added to an S3 bucket. You run terraform apply, and suddenly Terraform wants to destroy and recreate a production security group.

Nothing in your Git repository caused this. Someone made a quick hotfix directly in the cloud console two weeks ago, and now your real infrastructure no longer matches what Terraform believes exists.

If you manage cloud environments or are preparing for the HashiCorp Certified: Terraform Associate exam, understanding how Terraform state actually works—and how to recover cleanly when things drift—is the difference between routine deployments and a production outage.

Here is a practical walkthrough of how state breaks in real teams, how to prevent it, and how to fix drift safely without panicking.


Why terraform.tfstate Is the Single Most Sensitive File in Your Repo

Terraform is declarative. To decide what to create, update, or destroy, it compares three things during every run:

  1. Your HCL code (what you want)
  2. The live cloud API (what actually exists right now)
  3. The state file (terraform.tfstate) (the mapping between your HCL resources and real cloud resource IDs)

When beginners run Terraform locally, the state file sits on their laptop. That creates three immediate problems in a team environment:

  • Secrets exposure: State files often store plaintext metadata, connection strings, or generated passwords. Committing terraform.tfstate to Git is a major security risk.
  • No single source of truth: Two engineers running terraform apply from separate laptops will overwrite each other's changes.
  • State corruption: If two pipelines write to the state file at the exact same second, the JSON structure can break mid-write.

Step 1: Move State to an Encrypted Remote Backend

The first production rule of Terraform is simple: never store shared state locally. Use a remote backend such as an AWS S3 bucket, Azure Storage Account, or HCP Terraform with encryption at rest and object versioning enabled.

Object versioning is your safety net—if a state file ever gets corrupted or overwritten by mistake, you can roll back to the previous version in seconds.

terraform {
  backend "s3" {
    bucket       = "prod-infra-terraform-state"
    key          = "network/terraform.tfstate"
    region       = "ap-south-1"
    encrypt      = true
    use_lockfile = true
  }
}
Enter fullscreen mode Exit fullscreen mode

(Note: Modern Terraform versions support native S3 lockfiles via use_lockfile = true, removing the need to maintain a separate DynamoDB table just for state locking—though older environments and exam questions still reference DynamoDB locking as well.)


Step 2: Understand State Locking (and When Not to Force-Unlock)

When a CI/CD pipeline or engineer runs terraform apply, Terraform acquires a lock on the remote state. If a teammate runs apply ten seconds later, Terraform blocks the second run until the first finishes.

Occasionally, a runner crashes or a laptop loses Wi-Fi mid-apply, leaving a stale lock behind. You will see an error referencing a Lock ID.

Before you ever touch terraform force-unlock <LOCK_ID>:

  • Verify no pipeline is still running in GitHub Actions, GitLab CI, or Jenkins.
  • Confirm with your team that nobody is mid-apply.

Forcing an unlock while another apply is still mutating cloud resources is one of the fastest ways to corrupt state and end up with orphaned resources.


Step 3: Detect Drift Safely Without Mutating Anything

Configuration drift happens whenever someone clicks around in the AWS Console, Azure Portal, or CLI to apply an emergency fix without updating Terraform code.

Instead of blindly running terraform apply and letting Terraform revert an urgent firewall rule, start with a read-only refresh check:

terraform plan -refresh-only
Enter fullscreen mode Exit fullscreen mode

This command queries the live cloud provider, compares it against your current state file, and shows you exactly what changed outside Terraform—without proposing any destructive changes to your live infrastructure.

From there, you have two clean choices:

  1. The manual change was a mistake: Run a normal terraform apply so Terraform restores the infrastructure to match your Git repository.
  2. The manual change needs to stay: Update your .tf files to match the real-world change, then run terraform apply -refresh-only (or a regular plan/apply) so code, state, and live cloud are back in sync.

Step 4: Recovering Without Destroying Live Resources

Two real-world situations trip up both engineers and Terraform Associate exam candidates:

Case A: A Resource Was Created Manually and Needs to Be Managed by Terraform

Do not delete it and recreate it. Bring it under Terraform management using a declarative import block (preferred over the older CLI-only terraform import because it can be reviewed in pull requests):

import {
  to = aws_security_group.web_sg
  id = "sg-0123456789abcdef0"
}
Enter fullscreen mode Exit fullscreen mode

Run terraform plan to verify Terraform recognises the existing resource without forcing a replacement, then apply.

Case B: You Renamed a Resource or Refactored Code Into a Module

If you rename aws_instance.app to aws_instance.web_app in your code, Terraform assumes you want to destroy the old server and build a new one.

Prevent downtime by adding a moved block so Terraform updates the address inside the state file without touching the live server:

moved {
  from = aws_instance.app
  to   = aws_instance.web_app
}
Enter fullscreen mode Exit fullscreen mode

Quick Checklist Before Your Next terraform apply

  • Is remote state stored with encryption and versioning enabled?
  • Is state locking active so concurrent CI/CD jobs cannot collide?
  • Did you check terraform plan -refresh-only after an incident hotfix?
  • Are you using moved and import blocks instead of risking accidental resource replacement?

Mastering state management is not just a high-weightage domain on the HashiCorp Certified: Terraform Associate exam—it is the skill that keeps production deployments boring, predictable, and reversible. If you are planning to pair IaC skills with a primary cloud track, this AWS vs. Azure certification comparison guide breaks down how both cloud ecosystems structure their paths and renewal rules.


Related Reading in This Series

Top comments (0)