Nested for loop help

I can’t seem to figure out how to implement a nested for loop for a for_each to create EBS volumes. I have created the instances using count, but want to avoid index issues on volumes. Say I have var.replicas = 3 and var.raid_volumes = 8, I want to create instance-[instance]-[volume], so I should have 24 volumes total. Ideally it would be also nice to be able to access the instance number so I can select it for the availability zone. Any ideas how to implement this?

My last attempt:
for_each = toset([for i in range(var.replicas) : [for d in range(var.raid_volumes) : format(“%s-%s-data-%s”, var.name, i, d)]])

Thanks in advance.

Hi @DennoVonDiesel,

Instead of flattening nested loops, I think the setproduct function is what you are looking for. Maybe something like this?

[ for v in setproduct(range(var.replicas), range(var.volumes)) : format("%s-%d-data-%d", var.name, v[0], v[1]) ]

Which outputs values like:

[
  "test-0-data-0",
  "test-0-data-1",
  "test-0-data-2",
...
  "test-1-data-1",
  "test-1-data-2",
...
1 Like

Much thanks! That’s it!