Loops and iterations
There are three different ways to iterate within HCL. The most common are two meta-arguments, for_each
and count
, which operate on a resource, module, or data source block. At the same time, the third option uses the for
expression, which operations on any collection.
Count
The count
meta-argument is Terraform’s oldest method of iterating resources: an oldie but a goodie. The count
meta-argument is excellent when you want to provision the same block multiple times and have no unique identifier to key off of. In this situation, you will use the item’s index in a list to determine its uniqueness. This approach can pose challenges in the future if the items in the list need to change in such a way that would cause the indices of each item to change.
The best way to manage this is to treat your list as append-only, as this will avoid replacing related resources. Adding or removing items from the middle of the list will cause all the items below...