Preface
The most common ways to iterate and create similar resources from a single terraform resources definition are :
count
1 | resource "aws_instance" "server" { |
for_each
1 | resource "aws_iam_user" "the-accounts" { |
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 | resource "null_resource" "this" { |
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.