Preface

The most common ways to iterate and create similar resources from a single terraform resources definition are :

count

1
2
3
4
5
6
7
resource "aws_instance" "server" {
# Create one instance for each subnet
count = length(var.subnet_ids)
ami = "ami-a1b2c3d4"
instance_type = "t2.micro"
subnet_id = var.subnet_ids[count.index]
}

for_each

1
2
3
4
resource "aws_iam_user" "the-accounts" {
for_each = toset(["Todd", "James", "Alice", "Dottie"])
name = each.key
}

Both of these provide options for creating instances of similar resources leveraging a single resource block.

Challenge with count

count is helpful for scenarios where resources are provisioned based on a decision like the following

1
2
3
4
5
6
resource "null_resource" "this" {
count = var.env = 'prod' ? 1 : 0
}

here count is determined on basis of the value of var.env

The resource created with count is referenced using the count index. This means we should never use count against an ordered list.

I did this at one place and unknowingly one of the dev’s changed the sequence, this small change caused some of the resources to recreate

The terraform documentation itself says to use count only when resources are almost similar. I found the hard way what it means.

Recreating resources on each order change in the list was a big mess and caused a lot of issues. Lesson learnt to use for_each as much as possible.