Terraform Loops (for, for each)
1. Loops with count
As the name suggests we need to use count
but to use the count
first we need to declare collections inside our terraform file.
Let’s create a collection variable of type list(string)
–
variable "user_names" {
description = "IAM usernames"
type = list(string)
default = ["user1", "user2", "user3"]
}
Here is the pictorial representation of the above list variable
–
In the above collection, we have created a list
of type string
which contains usernames and these usernames we are going to use for creating aws_iam_user
.
The code snippet shows how we are going to iterate over the list(string)
–
resource "aws_iam_user" "example" {
count = length(var.user_names)
name = var.user_names[count.index]
}
terraform loop and for_each loop
Here is the complete terraform
file –
variable.tf
main.tf
2. Loops with for_each
The for_each
is a little special in terraforming and you can not use it on any collection variable.
Note : – It can only be used on set(string)
or map(string)
.
The reason why for_each
does not work on list(string)
is because a list can contain duplicate values but if you are using set(string)
or map(string)
then it does not support duplicate values.
Let’s first create a set(string)
variable –
3. for loop
The for
loop is pretty simple and if you have used any programming language before then I guess you will be pretty much familiar with the for
loop.
Only the difference you will notice over here is the syntax in Terraform.
I am going to take the same example by declaring a list(string)
and adding three users to it – user1
, user2
, user3
How to iterate over MAP?
We can use a similar approach to iterate over the map
also. But always keep in mind you need to specify the type of the map
like string
or number
.
Here is the same example which I have taken but modified a bit for map
–
Here is the difference between list and map syntax
For list –
{for <ITEM> in <LIST> : <OUTPUT_KEY> => <OUTPUT_VALUE>}
For Map –
{for <KEY>, <VALUE> in <MAP> : <OUTPUT_KEY> => <OUTPUT_VALUE>}