Menu

Terraform count vs for_each: why deleting one item rebuilt my resources
📰

Terraform count vs for_each: why deleting one item rebuilt my resources

DEV Community: terraform·DevOps in Practice·3 days ago
#IEiuinx7
Long article (843 words) — no AI summary yet.
Reading 0:00
15s threshold

You have three services in a list. You remove one. You expect Terraform to delete one thing.

Instead the plan says it will replace one resource and destroy another. If those were databases or load balancers, that's an outage.

This post shows exactly why that happens with count , how for_each avoids it, and how to switch existing code from one to the other without rebuilding anything. Every command and output below is from a real run on Terraform 1.17.

Reproducing the problem with count

Three files from one list, created with count :

variable "services" { default = [ "web" , "api" , "db" ] }

resource "local_file" "svc" { count = length ( var . services ) filename = "${var.services[count.index]}.txt" content = var . services [ count .…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.