Attach security groups to existing instance with AWS cli

In this post, we will learn command to attach security groups to existing instance with AWS cli. Working with command line is always fun. We can use the command in our scripts which also help us to do automation work.

Requirement :

1. AWS cli must be installed on system
2. Access and secret keys must be configured with AWS cli.

Attach single security group to instance

To attach single security group to instance use the following command syntax:

aws --region  ec2 modify-instance-attribute --instance-id  --groups 

Note: This is very important to know, when we attach the single security group to existing instance with above command, it will remove the existing security group. Hence, number of security group attached count will remain one.

Example to attach single security group to instance.

aws --region us-east-1 ec2 modify-instance-attribute --instance-id i-99b53065 --groups sg-44ae3520

Attach multiple security group to instance

To attach multiple security group to instance use the given below syntax.

aws --region  ec2 modify-instance-attribute --instance-id  --groups "" "" "" ...

Example to attach mutiple security group to instance.

aws --region us-east-1 ec2 modify-instance-attribute --instance-id i-99b53065 --groups "sg-44ae3520" "sg-2322ab47" "sg-05ae3561"