DEV Community

Cover image for How to use count in Terraform
Dennis Groß (he/him)
Dennis Groß (he/him)

Posted on

How to use count in Terraform

The count meta argument is an alternative to for_each and applies a resource multiple times.

resource "aws_route" "private_subnet" {
  count = local.subnet_count
  route_table_id = aws_route_table.private_subnet.id
  destination_cidr_block = "0.0.0.0/0"
  nat_gateway_id = aws_nat_gateway.natgw[count.index].id
}
Enter fullscreen mode Exit fullscreen mode

The snippet above uses the count meta arg to create multiple private subnets. You need to provide an integer value to the count argument and the resource will be applied according to the value that you choose.

You can combine the count with the length(..) function to get the amount of elements from a list and apply the same amount of resources.

resource "aws_route" "private_subnet" {
  count = length(var.availability_zones)
  route_table_id = aws_route_table.private_subnet.id
  destination_cidr_block = "0.0.0.0/0"
  nat_gateway_id = aws_nat_gateway.natgw[count.index].id
}
Enter fullscreen mode Exit fullscreen mode

This also works with maps when you use the length(..) function on keys or values.

you can access the index value (1,2,…) through count.index which is useful for enumerating resource names or accessing elements with the element(...) function from an array (i.e. array ob CIDR ranges).

Use the count meta argument over for_each if you have a simple resource use case that does no rely on multiple values but only operates with an index value.

Top comments (0)