Loops

Terraform does not have for-loops like other traditional procedural languages.

However, Terraform resource has a meta-parameter called “count”. This parameter defines how many copies of the resource to create.

Therefore, you can create multiple EC2 Instances as follows:

resource "aws_instance" "webserver" {
  count = 5
  ami = "ami-2d39803a"
  instance_type = "t2.micro"
}

With above configuration, all 5 instances will be identical. If you want to give each one a unique name, you can use “count.index” to get the index of each “iteration” in the loop.

resource "aws_instance" "webserver" {
  count = 5
  ami = "ami-2d39803a"
  instance_type = "t2.micro"
  tags {
    Name = "webserver-${count.index}"
  }
}

In the above code, index starts from zero and the instances will be named as webserver-0, webserver-1 … webserver-4.

You can also combine count.index with other interpolation functions and you can customize each iteration of the loop.

If you want to create each instances in different availability zone, you can accomplish by using count.index and the element function as follows :

With list variable

variable "region" {
  default = "us-east-1"
}

variable "azs" {
  type = "list"
  default = ["us-east-1a", "us-east-1b", "us-east-1c"]
}
resource "aws_instance" "webserver" {
  count = 10
  ami = "ami-2d39803a"
  instance_type = "t2.micro"
  availability_zone = "${element(var.azs, count.index)}"
  tags {
    Name = "webserver-${count.index+1}"
  }
}

With data source

variable "region" {
  default = "us-east-1"
}
data "aws_availability_zones" "azs" {}
resource "aws_instance" "webserver" {
  count = 10
  ami = "ami-2d39803a"
  instance_type = "t2.micro"
  availability_zone = "${element(data.aws_availability_zones.azs.names, count.index)}"
  tags {
   Name = "webserver-${count.index+1}"
  }
}

 

Here the count (10) is grater than no.of availability zones(3). In this case, element function will automatically “wrap” around using a standard mod function.

Therefore the above code will create 10 EC2 Instances, with 4 of them in us-east-1a, 3 in us-east-1b, and 3 in us-east-1c.

And the names will be webserver-1 to webserver-10 becase we added 1 to the index value.

If you want output the IP addresses of all 10 EC2 Instances, use * wildcads as below :

output "public_ips" {
  value = ["${aws_instance.wevserver.*.public_ip}"]
}
Advertisements

Learn Technology

%d bloggers like this: