In the examples in this blog post, you made extensive use of the count parameter and for_each expressions in loops and if-statements. This works well, but there’s an important limitation that you need to be aware of: you cannot reference any resource outputs in count or for_each.
Imagine that you want to deploy multiple EC2 Instances, and for some reason you didn’t want to use an ASG. The code might look like this:
resource "aws_instance" "example_1" {
count = 3
ami = "ami-0fb653ca2d3203ac1"
instance_type = "t2.micro"
}
Because count is being set to a hardcoded value, this code will work without issues, and when you run apply, it will create three EC2 Instances. Now, what if you want to deploy one EC2 Instance per Availability Zone (AZ) in the current AWS region? You could update your code to fetch the list of AZs using the aws_availability_zones data source and use the count parameter and array lookups to “loop” over each AZ and create an EC2 Instance in it: