Day 8: Terraform Finally Makes Sense (Loops, Count, For_Each & Dependencies)
Source: Dev.to
Overview
Today was one of those days where everything just clicked. I finally understood Terraform meta‑arguments—especially count, for_each, and depends_on. After some hands‑on practice, the concepts that once seemed scary turned out to be simple and powerful.
Using count
count is great for iterating over lists. In the example below, a list of bucket names is supplied via a variable, and count.index is used to create two S3 buckets:
resource "aws_s3_bucket" "bucket5" {
count = 2
bucket = var.bucket_name[count.index]
tags = var.tags
}
Running the typical Terraform workflow:
terraform plan
terraform apply --auto-approve
terraform output
produced the expected resources without any drama.
Using for_each
When you need unique resource names, for_each works cleaner with sets. The following snippet demonstrates creating two more S3 buckets using a set and referencing each bucket name with each.value:
resource "aws_s3_bucket" "bucket_set" {
for_each = var.bucket_set # a set of bucket names
bucket = each.value
tags = var.tags
}
Managing Dependencies with depends_on
Explicit dependencies ensure Terraform doesn’t rush resources in the wrong order. Adding depends_on guarantees that a resource waits for another to be fully provisioned before proceeding:
resource "aws_s3_bucket" "dependent_bucket" {
bucket = "my-dependent-bucket"
depends_on = [
aws_s3_bucket.bucket5
]
}
Clean Outputs with For‑Expressions
For‑expressions make output values concise and readable. The example below collects the names of all buckets created with count:
output "s3_bucket_names" {
value = [for bucket in aws_s3_bucket.bucket5 : bucket.bucket]
}
The output is a tidy list of bucket names, suitable for downstream consumption.
Takeaways
count– ideal for iterating over ordered lists.for_each– cleaner when you need unique identifiers, especially with sets.depends_on– prevents Terraform from applying resources out of order.- For‑expressions – produce neat, professional outputs.
The more I practice Terraform, the more confident I feel about doing DevOps work. “Okay… I can actually do this DevOps thing.”