Resources: count, for_each and lifecycle
How Terraform decides to create, update, replace or destroy, how to make many resources with count and for_each (and why for_each is usually safer), and how lifecycle rules protect what matters.
By the end of this lesson you'll be able to
0 of 5 completeVerified lab: the for_each and count plans, the count-vs-for_each comparison, prevent_destroy and the duplicate-name error. Run on Terraform 1.17.1; the output shown is real.
Code walkthrough: the AWS depends_on example and create_before_destroy: explained, not run.
Cloud lab: depends_on with IAM needs an AWS account.
A resource is one thing Terraform manages: a file, a server, a DNS record. This lesson is about how Terraform decides what to do with each one on every run, how to create many from one block, and how to stop it from deleting the things you can't afford to lose.
Resource behaviour
On each plan, Terraform compares three things for every resource: your configuration, the state (what it created last time) and the real object (refreshed through the provider). Then it picks one action:
| Symbol | Action | When |
|---|---|---|
+ | create | In the config, not in state |
~ | update in place | An argument changed, and the API can change it on the live object |
-/+ | replace | An argument changed that the API can't change in place |
- | destroy | In state, no longer in the config |
<= | read | A data source (lesson 11) |
Whether a change is an update or a replace isn't up to you: the provider decides. In the plan,
Terraform marks the argument that caused it with # forces replacement:
# local_file.inventory must be replaced -/+ resource "local_file" "inventory" { ~ content = <<-EOT server: model-kiwi EOT -> (known after apply) # forces replacement
For local_file, any content change replaces the file. For an EC2 instance, changing the
instance_type updates in place (with a stop and start), while changing the ami replaces it, and
the old server and its local disk are gone. Always find out why a -/+ happens before you approve
it.
count and for each
Two meta-arguments (they work on any resource type) create several resources from one block.
count: N copies by position
resource "local_file" "worker" { count = var.replicas # 0 means none: a common on/off switch filename = "${path.module}/out/${local.prefix}-worker-${count.index}.txt" content = local.common }
Inside the block, count.index is 0, 1, 2... The resources are addressed local_file.worker[0],
local_file.worker[1] and so on.
for_each: one per key
variable "servers" { type = map(string) default = { web = "t3.micro" api = "t3.small" } } resource "local_file" "server" { for_each = var.servers filename = "${path.module}/out/${local.prefix}-${each.key}.txt" content = "${local.common}size: ${each.value}\n" }
for_each takes a map or a set of strings. Inside, each.key and each.value are the
current entry, and the resources are addressed by key: local_file.server["web"]. From the lab's
plan:
# local_file.server["api"] will be created + resource "local_file" "server" { + content = <<-EOT managed-by: terraform env: dev size: t3.small EOT + filename = "./out/shop-dev-api.txt"
Why for_each is usually safer
The same three users, once with count and once with for_each. Then remove the first user:
variable "users" { type = list(string) default = ["asha", "ravi", "meera"] } resource "local_file" "by_count" { count = length(var.users) filename = "${path.module}/out/count-${count.index}.txt" content = var.users[count.index] } resource "local_file" "by_each" { for_each = toset(var.users) filename = "${path.module}/out/each-${each.key}.txt" content = each.key }
The real plan with users = ["ravi", "meera"], trimmed to the important lines:
# local_file.by_count[0] must be replaced ~ content = "asha" -> "ravi" # forces replacement # local_file.by_count[1] must be replaced ~ content = "ravi" -> "meera" # forces replacement # local_file.by_count[2] will be destroyed # (because index [2] is out of range for count) # local_file.by_each["asha"] will be destroyed # (because key ["asha"] is not in for_each map) Plan: 2 to add, 0 to change, 4 to destroy.
With count, Ravi moved from index 1 to 0 and Meera from 2 to 1, so both are replaced, and
index 2 is destroyed: three resources touched to remove one person. With for_each, only asha is
destroyed. On real infrastructure, count would have replaced two healthy servers.
Rule: use count for "N identical things" or a 0/1 switch. Use for_each whenever items have
identities (names, regions, users).
Lifecycle
The lifecycle block changes how Terraform handles one resource:
| Setting | What it does | Typical use |
|---|---|---|
prevent_destroy = true | Any plan that would destroy it fails | Databases, state buckets, DNS zones |
create_before_destroy = true | On replace, create the new one first, then destroy the old | Anything behind a load balancer, certificates |
ignore_changes = [tags] | Ignore drift in these arguments | Values changed by another system, like an autoscaler's desired_capacity |
replace_triggered_by = [...] | Replace this when another resource changes | Restart a service when its config changes |
Here's prevent_destroy stopping a real terraform destroy:
resource "local_file" "database" { filename = "${path.module}/out/${local.prefix}-database.txt" content = "do not delete\n" lifecycle { prevent_destroy = true } }
$ terraform destroy -auto-approve -var-file=dev.tfvars Error: Instance cannot be destroyed on main.tf line 34: 34: resource "local_file" "database" { Resource local_file.database has lifecycle.prevent_destroy set, but the plan calls for this resource to be destroyed. To avoid this error and continue with the plan, either disable lifecycle.prevent_destroy or reduce the scope of the plan using the -target option.
terraform destroy -auto-approve -var-file=dev.tfvarsterraforminfrastructure as codedestroydelete everything it manages-auto-approveskip the yes prompt
The whole destroy stopped, not just that one file. That's the point: it forces a human to edit the code and explain why in a pull request.
Without create_before_destroy, a replace destroys first and creates second, which means downtime.
With it, the new object comes up first. It needs names that can briefly exist twice, which is why
many AWS resources offer name_prefix instead of a fixed name.
Explicit dependencies
Most of the time references order the graph for you. depends_on is for a dependency Terraform
can't see. The classic case: an EC2 instance whose startup script reads from S3 needs the IAM policy
attached first, but nothing in the instance's arguments refers to the policy attachment.
resource "aws_instance" "app" { ami = data.aws_ami.ubuntu.id instance_type = "t3.micro" iam_instance_profile = aws_iam_instance_profile.app.name depends_on = [aws_iam_role_policy_attachment.read_s3] }
Use it sparingly. Every depends_on makes Terraform more cautious and plans less precise, and a
missing reference is often the better fix.
Read every -/+ and - in a plan before approving it, and ask why. Put prevent_destroy on
stateful resources, and turn on the cloud's own deletion protection too (for example
deletion_protection = true on RDS), since lifecycle rules only protect against Terraform.
When it goes wrong
Two resources with the same address. Copy-pasting a block and forgetting to rename it:
$ terraform validate Error: Duplicate resource "local_file" configuration on main.tf line 19: 19: resource "local_file" "note" { A local_file resource named "note" was already declared at main.tf:13,1-29. Resource names must be unique per type in each module.
terraform validateterraforminfrastructure as codevalidatecheck the configuration
Fix: give the copy its own name. If it should be several of the same thing, use for_each.
An unexpected replacement in the plan. You changed one argument and the plan shows -/+. Find the
line marked # forces replacement: that argument can't change in place. Decide before applying:
accept the replacement (with create_before_destroy to avoid downtime), revert the change, or, if
only the name in your code changed, use a moved block (lesson 8) instead.
prevent_destroy blocks a run you meant. The error names the resource. Remove prevent_destroy in
a reviewed change, apply, and put it back if the resource should stay protected. Never work around it
with -target on production without a second person agreeing.
See the count index shift yourself
Create the by_count and by_each resources from this lesson with three users, apply, then plan with the first user removed. Write down how many resources each approach would destroy and replace, and which approach you'd use for servers.
~/count-vs-foreach.txtReveal one safe solution
$ terraform apply -auto-approve $ terraform plan -var='users=["ravi","meera"]' -no-color | grep -E '# local_file|Plan:' > ~/count-vs-foreach.txt $ cat ~/count-vs-foreach.txt
terraform apply -auto-approveterraforminfrastructure as codeapplymake the changes-auto-approveskip the yes prompt
terraform plan -var='users=["ravi","meera"]' -no-color | grep -E '# local_file|Plan:' > ~/count-vs-foreach.txtplanpreview changes|pipe: send output to the next commandgrepfind lines that match a pattern>write output to a file, replacing it
cat ~/count-vs-foreach.txtcatprint a file
The lab's plan was 2 to add, 0 to change, 4 to destroy: count replaced two files and destroyed
one, for_each destroyed only asha. For servers, users or anything with a name, use for_each.
Try it yourself
0 of 5 steps doneRun each task in your own account or terminal, then tick it off.
Quick check
A plan shows -/+ next to a resource. What will happen?
Official reading for this lesson
Or get every quiz answer right and it completes itself.
Something unclear, wrong or out of date in this lesson? Tell me, and I'll fix it.