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"
}
###### 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.
# 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}"
}
}