Using Loops with `for_each` and `count`
Learn to provision multiple instances of a resource or module using `count` and `for_each` to handle collections and maps efficiently.
Using Loops with `for_each` and `count` is a free DevOps Bootcamp lesson on CoddyKit — lesson 1 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the DevOps Bootcamp learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Introduction to Loops
When managing infrastructure with Terraform, you often need to create multiple similar resources. Imagine needing 10 web servers or 5 database instances. Writing the same code block repeatedly would be tedious and error-prone!
This lesson introduces two powerful Terraform features: count and for_each. They help you provision multiple resources efficiently, keeping your configurations clean and scalable.
Why Use `count` and `for_each`?
Using loops like count and for_each offers significant benefits:
- Reduced Duplication: Write infrastructure code once and reuse it.
- Improved Readability: Your configurations become much cleaner and easier to understand.
- Scalability: Easily adjust the number of resources by changing a single value or collection.
- Consistency: Ensure all similar resources are configured identically.
`count` for Simple Repetition
The count meta-argument is perfect when you need to create multiple nearly identical instances of a resource or module. You provide an integer value, and Terraform creates that many instances.
Each instance created by count will have an index, starting from 0 up to count - 1. You can access this index using count.index.
Example: Multiple EC2 Instances with `count`
Let's provision three identical AWS EC2 instances. Notice how count.index is used to give each server a unique name.
provider "aws" {
region = "us-east-1"
}
resource "aws_instance" "web_server" {
count = 3
ami = "ami-053b0dcd10dcf2f56" # Ubuntu Server 20.04 LTS
instance_type = "t2.micro"
tags = {
Name = "WebServer-${count.index}"
}
}Understanding `count.index`
In the previous example, ${count.index} automatically resolved to 0, 1, and 2 for each instance. This allows you to create unique identifiers or adjust properties for each instance.
Without count.index, all three servers would have the exact same 'Name' tag, which might lead to confusion or issues in AWS.
Introducing `for_each`
While count is great for simple repetition, for_each offers more flexibility. It iterates over a set of strings or a map of strings, creating one instance for each element.
for_each is ideal when you need to manage resources with distinct configurations or when the number of resources is determined by a non-numeric collection (e.g., a list of environment names, or a map of user settings).
Example: `for_each` with a Set
Here, we create three S3 buckets, each named after an element in our for_each set. We use each.value to access the current item in the iteration.
provider "aws" {
region = "us-east-1"
}
resource "aws_s3_bucket" "app_buckets" {
for_each = toset(["prod-app-data", "dev-app-logs", "test-app-assets"])
bucket = each.value
acl = "private"
tags = {
Environment = split("-", each.value)[0]
}
}Example: `for_each` with a Map
Using a map allows you to define more complex, unique configurations for each resource. Here, we create S3 buckets with different versioning settings based on environment keys.
You can access the key with each.key and the value with each.value.
provider "aws" {
region = "us-east-1"
}
resource "aws_s3_bucket" "configured_bucket" {
for_each = {
production = { name = "prod-data-bucket", versioning = true }
development = { name = "dev-logs-bucket", versioning = false }
}
bucket = each.value.name
acl = "private"
versioning {
enabled = each.value.versioning
}
tags = {
Environment = each.key
}
}`count` vs. `for_each`: Choosing Wisely
When should you use which?
- Use
count: For simple numeric iteration, creating identical resources where the quantity is the primary concern. It's good when you only need an index to differentiate. - Use
for_each: For iterating over complex collections (sets or maps), when resources need unique identifiers or properties derived from the collection elements. It's generally preferred when each instance has a clear, unique logical identifier.
Quick Check: Loops
Consider a scenario where you need to create an S3 bucket for each team in your organization, and each bucket needs a specific retention policy defined by that team.
Recap: Efficient Resource Creation
Great job! You've learned how to leverage count and for_each to make your Terraform configurations more dynamic and efficient.
countis for simple, numeric repetition of identical resources, usingcount.indexfor differentiation.for_eachis for iterating over sets or maps, creating distinct resources with unique properties usingeach.keyandeach.value.
These constructs are fundamental for managing scalable and maintainable infrastructure as code!
Frequently asked questions
Is the “Using Loops with `for_each` and `count`” lesson free?
Yes — the full text of “Using Loops with `for_each` and `count`” is free to read here on the web, and the DevOps Bootcamp course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the DevOps Bootcamp course, upgrade to CoddyKit PRO.
What will I learn in “Using Loops with `for_each` and `count`”?
Learn to provision multiple instances of a resource or module using `count` and `for_each` to handle collections and maps efficiently. You practise DevOps Bootcamp with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start DevOps Bootcamp?
No prior experience is required. DevOps Bootcamp on CoddyKit is structured for beginners through advanced learners; this is — lesson 1 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Using Loops with `for_each` and `count`” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this DevOps Bootcamp lesson?
Yes. Every DevOps Bootcamp lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Using Loops with `for_each` and `count`
- Terraform Built-in Functions
- Conditional Expressions and Splats
- Dynamic Blocks for Nested Configuration