Home > Back-end >  How do I assign a new security group to an EC2 instance without removing the currently attached secu
How do I assign a new security group to an EC2 instance without removing the currently attached secu

Time:10-14

The AWS CLI command to attach a security group to running EC2 instance is as below.

aws ec2 modify-instance-attribute --instance-id i-12345 --groups sg-12345 sg-67890

But the above command will remove the currently attached security groups and attach the new one.

I have a use case where there are 100 servers and I have to attach a new security group to all those servers without detaching the current security groups.

How can I achieve this using the AWS CLI?

CodePudding user response:

The --groups does a complete replacement based on the arguments passed & there's no way to bypass this behaviour so you'll need to implement the logic of getting the existing security groups (SGs), appending the new SG on & then passing that as an input to --groups.

Confirmed by aws ec2 modify-instance-attribute documentation:

--groups (list)

[EC2-VPC] Replaces the security groups of the instance with the specified security groups. You must specify at least one security group, even if it’s just the default security group for the VPC. You must specify the security group ID, not the security group name.

(string)


This command should store all of the security groups for an instance with ID i-12345 in $securitygroups:

securitygroups=$(aws ec2 describe-instances --instance-ids i-12345 --query "Reservations[].Instances[].SecurityGroups[].GroupId[]" --output text)

The output of echo $securitygroups will look something similar to this:

sg-074bb9206bd7edaf2 sg-07cd92995b937cbd2 sg-05414d9cef32901be

Given that your new security group ID is sg-67890, execute the below command to append the new SG ID onto the list of security groups that we want to set (the space is important & needed):

securitygroups =" sg-67890"

The output of echo $securitygroups should now have the new SG ID appended:

sg-074bb9206bd7edaf2 sg-07cd92995b937cbd2 sg-05414d9cef32901be sg-67890

Finally, pass $securitygroups to the --groups option of aws ec2 modify-instance-attribute.

This variable will contain the existing assigned SG IDs as well as the new SG ID to be assigned so it'll be an assigning the new SG without unassigning any current SGs:

aws ec2 modify-instance-attribute --instance-id i-067a3aae02b8239e6 --groups $securitygroups

Put this in a loop for however many instances you have, problem solved.

  • Related