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 te...
1. Loops with count
As the name suggests we need to use
but to use the first we need to declare collections inside our terraform file.Let's create a collection variable of type
-Here is the pictorial representation of the above
-In the above collection, we have created a
of type which contains usernames and these usernames we are going to use for creating .The code snippet shows how we are going to iterate over the
-Here is the complete
file -provider "aws" {
region ="us-east-1"
}
resource "aws_instance" "ins1" {
count= length(var.instances)
ami = var.ami
instance_type = var.instance_type
tags = {
"Name" = var.instances[count.index]
}
}
2. Loops with for_each
The
is a little special in terraforming and you can not use it on any collection variable.Note : - It can only be used on or .
The reason why
does not work on is because a list can contain duplicate values but if you are using or then it does not support duplicate values.Let's first create a
variable -3. for loop
The
loop is pretty simple and if you have used any programming language before then I guess you will be pretty much familiar with the 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
and adding three users to it - , ,How to iterate over MAP?
We can use a similar approach to iterate over the
also. But always keep in mind you need to specify the type of the like or .Here is the same example which I have taken but modified a bit for
-Here is the difference between list and map syntax
For list -
For Map -
COMMENTS