Search code examples
amazon-web-servicesloopsterraformterraform-provider-aws

How do I iterate over a 'count' resource in Terraform?


In this example, I'm trying to create 3 EC2 instances which each have an elastic IP assigned. I want to achieve this by saying the following.

resource "aws_instance" "web_servers" {
  ami                         = "ami-09e67e426f25ce0d7"
  instance_type               = "t3.micro"
  ...
  count = 3
}

and, along with other networking instances,

resource "aws_eip" "elastic_ip" {
  for_each = aws_instance.web_servers
  instance = each.key
  vpc      = true
}

However, this is saying the following:

The given "for_each" argument value is unsuitable: the "for_each" argument must be a map, or set of strings, and you have provided a value of type tuple.

I have tried wrapping the for_each in a toset() which also says there is an issue with an unknown number of instances - I know there are 3 though. Is there something I'm missing around the count & for_each keywords?


Solution

  • If you really want to use for_each, rather then count again, it should be:

    resource "aws_eip" "elastic_ip" {
      for_each = {for idx, val in aws_instance.web_servers: idx => val}
      instance = each.value.id
      vpc      = true
    }
    

    But since you are using count in the first place, it would be probably better to use count for your aws_eip as well:

    resource "aws_eip" "elastic_ip" {
      count    = length(aws_instance.web_servers)
      instance = aws_instance.web_servers[count.index].id
      vpc      = true
    }