How to use count in Terraform

gdenn

Dennis Groß (he/him)

Posted on December 18, 2022

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.

💖 💪 🙅 🚩
gdenn
Dennis Groß (he/him)

Posted on December 18, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Use locals with Terraform
terraform Use locals with Terraform

December 20, 2022

How to configure Provider in Terraform
terraform How to configure Provider in Terraform

December 19, 2022

How to use templates in Terraform
terraform How to use templates in Terraform

December 18, 2022

How to use count in Terraform
terraform How to use count in Terraform

December 18, 2022