Foreach
In this lesson we'll discuss the advanced "foreach" resource.
We'll cover the following
Foreach#
The for_each
construct allows you to create a set of resources similar to what we have just seen before by using the count.
A for_each
statement is more useful when you are projecting a set of values
into a set of resources though.
Project example#
Let’s see an example:
A few things have changed from the count example. Firstly we have defined a local called “fruit” to hold a list of all of the names of queues we want to create. The value of the fruit is an array that we are then passing to the toset
function. We do this because the foreach operator only
works with a map or a set (we will see why shortly). A set is a distinct set of values, whereas a list can contain the same value multiple times. Inside the queues
resource, we use another special attribute, for_each
.
We set this to the value of our set. This tells Terraform that we want to run the code block once for each item in our set. To access the current value within the resource,
we can use the special value each.key
. To reference a created resource using a for_each
, we have to
index the value from the set. In the above example, we select the queue created with the
name apple by using ["apple"]
.
If you run this code you should see three queues created. Add another fruit (pear) after apple to the array that reads toset(["apple", "orange", "banana"])
and apply this change. You will notice that Terraform will want to create one extra queue for pear
. Even though we added the item pear
to the middle of the list, Terraform is clever enough to realise and only create one extra queue.