2
votes

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}"
  }
}
2

2 Answers

7
votes

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...
}
0
votes

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.