Ad space (banner)
AD

Got the fundamentals? A structured Terraform course is a fast way to level up.

Find Terraform courses on Udemy

Affiliate link. Costs you nothing extra.

Lesson 33 / 37

What Are for_each and count?

When you need several near-identical resources, count and for_each create them from one block instead of copy-paste.

count takes a number and gives you indexed instances; for_each takes a map or set and gives you instances keyed by name.

Three servers become one block with count = 3, addressed as aws_instance.web[0] and so on.

A common stumble is using count for a list that changes. Removing an item shifts every later index, so Terraform destroys and recreates resources that should have been left alone — for_each avoids this by keying on names.

In real work, for_each is the default choice for anything whose membership may change, and count is kept for simple fixed repetition or conditional creation.

Terraform
Try it (type this into the pseudo terminal)
terraform plan

🧑‍💻 You can type this command into the Terraform pseudo terminal to try it yourself (this page itself has no interactive terminal).

Ad space (banner)
Ad space (in-article)