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

Viewed 898

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?

2 Answers

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
}

In AWS is your instance field = EC2 ID = ARN?

If so you may be able to access the arn attribute in the aws_instance resource block.

You could try toset(aws_instance.web_servers.arn) and keep instance = each.key. I generally just use each.value but they should be the same when dealing with a set.

Related