'Terraform - Multiple subnets with same aws_instance resource

I'm attempting to deploy multiple EC2 instances, each in different subnets using the same aws_instance resource block.

When I set the count parameter to more than one server it establishes them all in the same subnet.

Is there a way to accomplish this via Terraform?

Below you'll find my Terraform block:

resource "aws_instance" "ec2-instance" {
  ami                    = "${var.ec2_ami}"
  instance_type          = "${var.instance_type}"
  key_name               = "${var.key_name}"
  vpc_security_group_ids = ["${var.security_group}"]

  subnet_id = "${var.subnet_id}"
  count     = "${var.count}"

  root_block_device {
    volume_size = "${var.root_volume_size}"
    volume_type = "${var.root_volume_type}"
  }

  tags {
    Name = "${var.app_name}"
  }
}


Solution 1:[1]

You have to define another aws_instance block to achieve that. AWS API also does not support this. When you create an EC2 instance using the RunInstances API, it will launch all instances (as part of the single request) in the same subnet.

Solution 2:[2]

I'm attempting to deploy multiple EC2 instances, each in different subnets using the same aws_instance resource block.

You can use the following workaround

data aws_subnet_ids current {
   vpc_id = var.vpc_id
}

resource "aws_instance" "ec2-instance" {
   count     = "${var.count}"
   subnet_id = tolist(data.aws_subnet_ids.current.ids)[count.index % length(data.aws_subnet_ids.current.ids)]

   # rest of config as before...
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 krishna_mee2004
Solution 2 ALex_hha