Program 1 - Terraform Looping using AWS

Content of first.tf


resource "aws_instance" "example" {
  ami = "ami-2d39803a"
  instance_type = "t2.micro"
}

###### WRONG ###### 
for i = 0; i < 3; i++ {
  resource "aws_instance" "example" {
    ami = "ami-2d39803a"
    instance_type = "t2.micro"
  }  
}

###### RIGHT ###### 
resource "aws_instance" "example" {
  count = 3
  ami = "ami-2d39803a"
  instance_type = "t2.micro"
}

Program 2 - Terraform Looping using AWS


###### OR ###### 

resource "aws_instance" "example" {
  count = 3
  ami = "ami-2d39803a"
  instance_type = "t2.micro"
  tags {
    Name = "example-${count.index}"
  }
}
The code above will create three EC2 Instances. They will be named “example-0”, “example-1” and “example-2”. If you combine count.index with some of the other interpolation functions built into Terraform, you can customize each “iteration” of the “loop” even more.

Program 3 - Terraform Looping using AWS

If you were using a normal programming language with loops and arrays, you would configure each EC2 Instance to use a different AZ as follows:

# This is just pseudo code. It won't actually work in Terraform.
for (i = 0; i < 3; i++) {
  resource "aws_instance" "example" {
    ami = "ami-2d39803a"
    instance_type = "t2.micro"
    availability_zone = "${azs[i]}"
    tags {
      Name = "example-${i}"
    }
  }  
}

# In Terraform, you can accomplish the same thing by using count.index and the element function:

resource "aws_instance" "example" {
  count = 3
  ami = "ami-2d39803a"
  instance_type = "t2.micro"
  availability_zone = "${element(var.azs, count.index)}"
  tags {
    Name = "example-${count.index}"
  }
}