After you’ve used count on a resource, it becomes an array of resources rather than just one resource. That means to read an attribute from a resource:
Example:
or use splat expression (”*”) to access all items in the array:
Limitations:
Can’t be used for inline blocks.
Can be tricky when values are removed from the array. For example:
If you try to remove the middle item, instead of removing resource that deployed with it, all resource array will be shifted:
for_each is better suited for these situations, as it will remove exact, instead of shifting everything to the left.
for_each expression
Loop over resources, inline blocks within a resource, and modules.
where COLLECTION is a set or map to loop over (lists are not supported when using for_each on a resource).
When for_each is used on the resource, it becomes a map of resources (instead of a single resource or an array of resources as with count):
To extract specific attribute for all resources in the map:
Inline blocks
To dynamically generate inline blocks:
where VAR_NAME is the name to use for the variable that will store the value of each “iteration,” COLLECTION is a list or map to iterate over, and the content block is what to generate from each iteration.
Use <VAR_NAME>.key and <VAR_NAME>.value within the content block to access the key and value, respectively, of the current item in the COLLECTION.
When you’re using for_each with a list, the key will be the index, and the value will be the item in the list at that index, and when using for_each with a map, the key and value will be one of the key-value pairs in the map.
Example:
for expression
Loop over lists and maps.
Lists
Syntax:
Examples:
Maps
Syntax:
Examples:
for string directive
Loop over lists and maps withing a string.
String directives allow you to use control statements (e.g., for-loops and if-statements) within strings using a syntax similar to string interpolations, but instead of a dollar sign and curly braces (${…}), you use a percent sign and curly braces (%{…}).
Syntax:
Example:
To get rid of the comma and space and the end, use [[Terraform conditionals#if-string-directive|if string directive]]: