How do I add multiple instances to aws_network_interface_sg_attachment?

614 Views Asked by At

I have the following code and would like to attach a security group to an Elastic Network Interface (ENI).

resource "aws_instance" "foo" {
  # us-west-2
  count = var.instances
  ami           = data.aws_ami.ubuntu.id
  instance_type = "t2.micro"
  key_name = aws_key_pair.deployer.key_name
  subnet_id  = aws_subnet.tf_test_subnet.id
  vpc_security_group_ids  = [ aws_security_group.allow_tls.id ]
}
resource "aws_network_interface_sg_attachment" "sg_attachment" {
  security_group_id    = aws_security_group.allow_tls.id
  network_interface_id = element(aws_instance.foo.*.primary_network_interface_id,0)
}

however upon deployment of the code I get

Error: security group sg-060153b203cbaa6d5 already attached to interface ID eni-006293e38b0056a91

I suspect that this may be because of the ,0 index value but I'm not sure?

so the question is how can I iterate over the instances and apply the security group to the ENI

1

There are 1 best solutions below

4
Dennis Traub On BEST ANSWER

Your template is actually trying to attach it twice:

  • Once as part of the aws_instance resource’s vpc_security_group_ids attribute,
  • and then again using the aws_network_interface_sg_attachment.

In your case, you don’t need the aws_network_interface_sg_attachment resource.