# Best Way to create a nested loop?

**URL:** <https://discuss.hashicorp.com/t/best-way-to-create-a-nested-loop/39205>\
**Category:** Terraform\
**Created:** [May 8, 2022, 5:48am UTC](https://discuss.hashicorp.com/t/best-way-to-create-a-nested-loop/39205 "2022-05-08T05:48:50Z")\
**Posts on this page:** 1\
**Showing post:** 2

<div class="post-metadata">

**Author:** ![maxb](https://sea2.discourse-cdn.com/hashicorp/user_avatar/discuss.hashicorp.com/maxb/32/26655_2.png) [@maxb](https://discuss.hashicorp.com/u/maxb)\
**Post date:** [May 8, 2022, 6:46am UTC](https://discuss.hashicorp.com/t/best-way-to-create-a-nested-loop/39205/2 "2022-05-08T06:46:55Z")

</div>

First: Upgrade. It might(?) not be strictly necessary to for this question, but the Terraform language went through major changes in 0.12 → 0.13. You’ll do yourself no favours waiting to cross this boundary, and if you have questions, you’ll find the collective knowledge of people who can help, is already on the wane, as this transition fades into the past.

Note that for existing Terraform state files, it is _required_ to upgrade specifically from 0.12 to 0.13, before moving on to any later versions.

(The docs actually claim the same about 0.13 to 0.14, though in _that_ case I believe it to be untrue - possibly copied forward from the previous release’s documentation without a true need.)

* * *

On to your question:

Since you have mentioned modulo, I guess that you are using the `count` attribute.

You should switch to using `for_each` so you can use string keys to identify each resource, rather than numbers, and avoid having to rely on attempting to pack multiple pieces of information into a single integer.

Here is an example I wrote recently showing how multiple Terraform `for` expressions can be used to create a map suitable for `for_each` using nested iteration: [Multiple iteration in one resource - #2 by maxb](https://discuss.hashicorp.com/t/multiple-iteration-in-one-resource/38612/2)

---

_[View the full topic](https://discuss.hashicorp.com/t/best-way-to-create-a-nested-loop/39205)._
