1
votes

I am creating 2 ec2 instances with terraform and I want to give secondary ip address to the first instance that terraform creates.

I am using below code block

resource "aws_network_interface" "floating_private" {
  subnet_id       = "${var.subnet_cluster_one}"
  private_ips_count = 2
}

resource "aws_instance" "instance_attrix_cluster_one" {
    count = 2
    instance_type = "${var.aws_instance_type}"
    ami = "${var.attrix_ami}"
    subnet_id = "${var.subnet_cluster_one}"
    security_groups = "${var.aws_security_groups}"
    key_name = "${var.ssh_key}"
    tags = "${merge(var.default_tags, map("Name", "${format("attrix%02d", 
count.index + 1)}-${var.env_name}"))}"
}

I tried to add below code in "aws_instance" block

network_interface = "${floating_private.id ? count.index == 0 : count.index >= 0}"

However, I am seeing the error below -

 Error reading config for aws_instance[instance_attrix_cluster_one]: floating_private.id: resource variables must be three parts: TYPE.NAME.ATTR in:

 ${floating_private.id ? count.index == 0 : count.index >= 0}

How can I set the network_interface attribute if the count == 0?

1

1 Answers

0
votes

Rather than creating two custom ENIs and attaching them to the first instance, I slightly altered the approach as so the default ENI is created with the instance and we attach an additional ENI to the first instance post creation of the instance.

Allow Terraform to create the default ENI for the instance then create an attachment for the first instance. See below.

resource "aws_network_interface" "floating_private" {
  subnet_id = "${data.aws_subnet.example.id}"
}

resource "aws_instance" "instance_attrix_cluster_one" {
  count         = 2
  instance_type = "t2.micro"
  subnet_id     = "${data.aws_subnet.example.id}"
  ami           = "${data.aws_ami.ubuntu.id}"

  tags {
      Name = "test-${count.index}"
  }
}

resource "aws_network_interface_attachment" "test" {
  instance_id          = "${element(aws_instance.instance_attrix_cluster_one.*.id, count.index)}"
  network_interface_id = "${element(aws_network_interface.floating_private.*.id, count.index)}"
  device_index         = "${count.index + 1}"
}

Slightly modified to do a bit of testing on my machine, but hopefully you get the idea and can apply to your solution.