Search code examples
amazon-web-servicesamazon-ec2aws-security-group

How can I change security group on EC2 via API?


I created a security group by using java SDK. Now, I want to add this security group to one of my EC2 instances. Is it possible via API???


Solution

  • Security Groups are associated with Elastic Network Interfaces (ENI), and ENIs are associated with instances:

    Instance -> ENI(s) -> Security Group(s)
    

    Therefore, you would use:

    ModifyNetworkInterfaceAttributeRequest request = 
         new ModifyNetworkInterfaceAttributeRequest()
           .withGroups("sg-903004f8", "sg-1a2b3c4d")
           .withNetworkInterfaceId("eni-686ea200");
    

    Use the ENI that is currently attached to the EC2 instance.

    See: Java modifyNetworkInterfaceAttribute()