⚡ ~/naveed Interview Prep
⚡ Portfolio Home 👤 About Naveed Bio & Credentials 📫 Contact Naveed Get In Touch ✍️ Engineering Blog Deep Dives 🎯 Interview Hub 1,000+ Scenarios ☸️ Kubernetes Mastery Hub 24 Modules 🎮 DevOps Arcade & Quizzes Subnet Blitz ⚡ 🗺️ DevOps Roadmaps PDFs & Guides 🤖 Morpheus Analysis AI Quant ↗ 🛠️ Developer Tools Utilities 🧪 Labs & Experiments 📄 Interactive CV & Certs 🔗 All Links & Socials ⚡ Join The Dispatch (Weekly SRE Newsletter) →
← Back to All Terraform & IaC Interview Questions Scenario 42 of 120 in Terraform & IaC
Senior DevOps / SRE [L2] Terraform Terraform Modules & State Production Scenario [L2]
🎯 Target Role / Context: Terraform Scenario #37 (L2) · Use VPC ID from another module

Q: You need to change a resource attribute that forces replacement but you want to minimize downtime. How?

Use create_before_destroy lifecycle:

#Terraform #L2 #IaC #Cloud Infrastructure
🎙️ Candidate Opening & Architectural Context
"When a resource attribute that forces replacement must change, minimise downtime by making Terraform create the new object before it destroys the old one with <code>lifecycle { create_before_destroy = true }</code>, avoiding name collisions, and shifting traffic gradually. The plan marks such attributes with <code># forces replacement</code>. Interviewers ask this to test whether you read plans carefully, know that replacement is destroy plus create by default, and recognise resources like databases where replacement means data loss and needs a different strategy entirely."
Advertisement
⚡ Recommended Practice Lab

Want to master this scenario in a live sandbox? KodeKloud's HashiCorp Certified Terraform Associate (003) Interactive Labs covers this exact problem with hands-on terminal drills.

🛠️ Production Runbook & Step-by-Step Resolution

Direct Answer: When a resource attribute that forces replacement must change, minimise downtime by making Terraform create the new object before it destroys the old one with <code>lifecycle { create_before_destroy = true }</code>, avoiding name collisions, and shifting traffic gradually. The plan marks such attributes with <code># forces replacement</code>. Interviewers ask this to test whether you read plans carefully, know that replacement is destroy plus create by default, and recognise resources like databases where replacement means data loss and needs a different strategy entirely.

1️⃣

Understand what forces replacement

Some attributes are immutable in the provider or the cloud API, so Terraform must recreate the object. Learning to spot these markers quickly is the single most useful habit for avoiding accidental outages from routine changes.

  • Read the plan: terraform plan shows # forces replacement next to the attribute and prints -/+ for destroy-and-recreate.
  • Default order: destroy first, then create. That is the source of the downtime for load balancers, security groups and instances.
  • Dependencies: everything that references the replaced object is updated too, which can cascade.
  • Data bearing resources: for databases and volumes, replacement deletes data unless you snapshot or migrate.
  • Common examples: renaming a resource with a fixed name, changing the subnet of an instance, or changing an immutable engine setting often trigger replacement; confirm with the provider documentation for that argument.
Pro Tip: Always read for <code>-/+</code> in the plan before approving, especially on stateful resources.
2️⃣

Hands-on: resource attribute that forces replacement with create_before_destroy

Reverse the order, and make names unique so both objects can coexist.

resource "aws_security_group" "app" {
  name_prefix = "app-"
  vpc_id      = var.vpc_id

  lifecycle {
    create_before_destroy = true
  }
}

resource "aws_lb_target_group" "app" {
  name_prefix = "app-"
  port        = 8080
  protocol    = "HTTP"
  vpc_id      = var.vpc_id

  lifecycle {
    create_before_destroy = true
  }
}
  • Lifecycle: create_before_destroy = true builds the replacement first, updates dependents, then deletes the old object.
  • Name collisions: if the name is fixed, creation fails because the old object still exists. Use name_prefix or add a suffix that changes with the replacement.
  • Propagation: Terraform applies the same ordering to dependencies of that resource, which is usually required but can surprise you.
  • Typical fit: security groups, launch templates, ACM certificates, target groups and instances behind a load balancer.
Advertisement
3️⃣

Control when and how replacement happens

Use Terraform's own tools to rehearse and sequence the change. These options let you rehearse the replacement on one object before committing the whole fleet.

terraform plan -out=tfplan
terraform show tfplan | grep -B2 "forces replacement"

terraform apply -replace="aws_instance.web[0]"

resource "aws_instance" "worker" {
  # ...
  lifecycle {
    replace_triggered_by = [aws_launch_template.worker.id]
  }
}
  • Force a rollout: terraform apply -replace="aws_instance.web[0]" replaces one instance deliberately, instead of the deprecated taint command.
  • Roll one at a time: for a fleet, replace a single instance, verify health, then continue, rather than changing all at once.
  • replace_triggered_by: make a resource replace when another changes (Terraform 1.2 and later), for example an instance refreshing when a related resource ID changes.
  • Preview: use terraform plan -out=tfplan and review it, then apply that exact plan.
  • Health checks: make sure the load balancer health check passes on the new target before the old one drains, otherwise create_before_destroy only moves the outage.
4️⃣

Failure modes and alternatives

Some resources cannot be made zero downtime by ordering alone. Decide before the change whether ordering alone is enough or a different migration pattern is needed.

  • Unique constraints: resources with fixed names, static IPs or unique ports fail with "already exists" under create_before_destroy.
  • Databases: do not replace in place. Take a snapshot, use blue/green or a read replica promotion, then repoint the application. Keep deletion_protection and a final snapshot enabled.
  • Avoid the change: if the attribute is not essential, use ignore_changes or keep the old value; accept drift knowingly.
  • Blue/green: create a parallel stack, shift DNS or load balancer weights, then remove the old stack in a later apply.
  • Dependents: replacing a resource changes its ID, so anything pinned to the old ID, such as allow lists or DNS records, must update in the same apply.
5️⃣

Production safeguards

Make destructive plans visible and hard to approve by accident. Guardrails matter most when a change is routine enough that reviewers stop reading the plan carefully.

  • Plan review gate: fail the pipeline or require extra approval when a plan contains deletes of tagged critical resources.
  • prevent_destroy: add it to critical stateful resources so a replacement attempt errors out instead of deleting.
  • Off-hours and canaries: schedule replacements and watch health checks and error rates during the change.
  • Staged rollouts: split the change into two pull requests when possible, first adding the new resource and shifting traffic, then removing the old one.
  • Backups and snapshots: take and verify a snapshot before touching any stateful resource, and know the restore time.
💡 The Senior SRE Gold Nugget (Key Architectural Takeaway)
"Pro-Tip: Pair <code>create_before_destroy</code> with <code>name_prefix</code>, and use <code>prevent_destroy</code> on stateful resources so a forced replacement stops the apply instead of deleting data."
⚡ 60-Second Elevator Pitch Talking Points
  • A resource attribute that forces replacement makes Terraform destroy then create; I flip the order with create_before_destroy and unique names.
  • I verify by reading the plan for -/+ and forces replacement, and by rolling one instance with apply -replace.
  • I automate plan review gates and use prevent_destroy or blue/green for stateful resources.
⛔ Critical Candidate Mistakes to Avoid in This Scenario

Senior hiring managers and bar raisers evaluate how you prioritize during outages. Avoid these common anti-patterns:

  1. Adding create_before_destroy with a fixed name The new object collides with the old one and the apply fails midway.
  2. Replacing a database in place Terraform deletes and recreates it, losing data unless you migrate via snapshots or blue/green.
  3. Using terraform taint in new workflows It is deprecated; use apply -replace so the plan is reviewable.
  4. Approving the plan without searching for -/+ A single changed immutable attribute can destroy production resources.
Advertisement
Want more Terraform & IaC scenarios?
Explore our complete collection of scenario-based Terraform & IaC interview runbooks.
Browse All Terraform & IaC Questions →