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}"
  }
}
In your terraform sample you are using count to create multiple instances of the resource, but are specifying the same subnet for each instance (var.subnet_id). 
You can use the count index to set resource properties to different values for each instance. For example, you can define your list of subnets as a variable and then use element() to pick one based on the count index.
variable "subnet_ids" {
  default =  [ "s1", "s2", "s3" ]
}
resource "aws_instance" "ec2-instance"
{
  count = "${var.count}"
  subnet_id = "${element(var.subnet_ids, count.index)}"
 # rest of config as before...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With