Abhishek Solanki
Abhishek Solanki

Reputation: 426

aws_network_interface_sg_attachment module on adding new SG , destroying existing SG

AWS instance , Elastic Network Interface (ENI) has existing security group (SG_main). Adding new SG (sg-01) using aws_network_interface_sg_attachment resource. sg-01 is getting added , SG_main has no affect on it.

Adding another sg-02 using aws_network_interface_sg_attachment resource. destroy's sg-01 , attaches sg-02 and SG_main(no change).

Is there any other module don't destroy existing SG or Is there any other way to achieve this.

Input variable -

sg_attachment = [
 {
    attach_security_group_id    = "sg-01"
 }
]

Input variables are given in above form , as I was planning to give multiple values later like below. ["sg-01","sg-02","sg-03"] -> will be mapped with EC2[0] ["sg-04","sg-05"] -> will be mapped with EC2[1] .. like wise.

sg_attachment = [
 {
    attach_security_group_id    = ["sg-01","sg-02","sg-03"]
 },
 {
    attach_security_group_id    = ["sg-04","sg-05"]
 }
]

resource block

resource "aws_network_interface_sg_attachment" "sg_attachment" {
  count = length(var.sg_attachment) != 0 ? length(var.sg_attachment) : 0
  security_group_id    = var.sg_attachment[count.index].attach_security_group_id
  network_interface_id = aws_instance.EC2[count.index].primary_network_interface_id
}

Upvotes: 2

Views: 353

Answers (1)

Marcin
Marcin

Reputation: 238867

Is there any other way to achieve this.

You would have to use aws_network_interface data source to query for the existing security_groups for your ENI.

data "aws_network_interface" "existing_sgs" {
  count = length(aws_instance.EC2)
  id = aws_instance.EC2[count.index].primary_network_interface_id
}

Once you have existing_sgs you would have to concat them with the new ones. Otherwise, the old ones get replaced with the new ones as you already observed.

Upvotes: 1

Related Questions