0
0
Terraformcloud~3 mins

Count vs for_each decision in Terraform - When to Use Which

Choose your learning style9 modes available
The Big Idea

What if you could create dozens of cloud resources by writing just one block of code?

The Scenario

Imagine you need to create multiple cloud resources, like servers or storage buckets, by writing each one separately in your configuration.

You copy and paste blocks of code, changing only names or IDs manually.

The Problem

This manual way is slow and boring.

It's easy to make mistakes like forgetting to update a name or creating duplicates.

When you want to add or remove resources, you must edit many places, which wastes time and causes errors.

The Solution

Using count or for_each lets you write one block of code that automatically creates many resources.

This saves time, reduces mistakes, and makes your setup easy to change.

Before vs After
Before
resource "aws_instance" "server1" { ... }
resource "aws_instance" "server2" { ... }
After
resource "aws_instance" "servers" {
  count = 2
  ...
}
What It Enables

You can quickly and safely manage many resources with simple, clear code that adapts as your needs grow.

Real Life Example

A company needs 10 identical virtual machines for a project.

Instead of writing 10 blocks, they use count = 10 to create all at once.

Later, they add 5 more by changing one number.

Key Takeaways

Manual resource creation is slow and error-prone.

count and for_each automate resource creation.

This makes infrastructure easy to scale and maintain.