How can I create multiple instances with 2 network interfaces on AWS?

Hi!

I’m just trying to create some AWS instances (count > 1) but I’m just wondering how could I create multiple instances based on count variable with 2 network interfaces each one:

My TF code is like:

resource "aws_instance" "myinstance"{
 count = "2"
 ....
}

resource "aws_network_interface" "firstnic" {
 subnet_id       = xxxx
 security_groups = xxxx
 attachment {
  instance     = "${aws_instance.myinstance[count.index].id}"
  device_index = "0"
 }
}

resource "aws_network_interface" "secondnic" {
 subnet_id       = xxxxx
 security_groups = xxxxx
 attachment {
  instance     = "${aws_instance.myinstance[count.index].id}"
  device_index = "1"
 }
}

So, if I try to validate this code I get this error for each network instance:

Error: Reference to "count" in non-counted context

  on xxxx.tf line 107, in resource "aws_network_interface" "firstnic":
 107:     instance     = "${aws_instance.myinstance[count.index].id}"

The "count" object can be used only in "resource" and "data" blocks, and only  when the "count" argument is set.

Any advice? How could I create two NICs for each instance?

Thx u all!

1 Like

I’m also facing same issue. luixtao, was you able to find fix for it ?

Generally, I find it’s better to use an autoscaling group, even with max 1 instance, rather than creating aws instances directly. I also prefer to create the ENIs in Terraform but leave the hosts to attach them on boot. YMMV

To answer your question- you can only use count.index in a resource which has the count attribute. In this case you could try something like:

locals {
  instance_count=2
  interfaces_per_instance=2
}
resource "aws_instance" "myinstance"{
 count = local.instance_count
 ....
}
resource "aws_network_interface" "nic" {
 count = local.instance_count * local.interfaces_per_instance
 subnet_id       = xxxx
 security_groups = xxxx
 attachment {
  instance     = "${aws_instance.myinstance[count.index % local.instance_count].id}"
  device_index = count.index % local.interfaces_per_instance
 }
}

I’m not sure of the math/aws provider syntax above but it should be doable with something along those lines.

It might also be better to use for_each on the resources but I haven’t played with it much yet.