0

This question is a follow up (not a duplicate) of How to add a security group to a running EC2 Instance?. I believe it deserves to have its own answer rather than a comment.

How could I write a one-liner using the AWS CLI to add a security group to an EC2.

Because the annoyance of using the command

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

is that it requires to specify all CURRENT and NEW SGs.

So which one-liner can I use to add a security group to the instance's current ones?

arod
  • 542
  • 6
  • 19

1 Answers1

2

We can start by doing

current_security_groups=$(aws ec2 describe-instances --instance-ids $newid --query Reservations[*].Instances[*].SecurityGroups[*].GroupId --output text)

Which gives us the current security group. For example:

$ echo $current_security_groups
sg-6ddf0b08 sg-7ee1231b

Then we can build upon the previous answer and write:

aws ec2 modify-instance-attribute --instance-id $newid \
   --groups $current_security_groups sg-e1395da9

Or in one line:

aws ec2 modify-instance-attribute --instance-id $newid \
  --groups $(aws ec2 describe-instances \
     --instance-ids $newid \
     --query Reservations[*].Instances[*].SecurityGroups[*].GroupId \
     --output text) \
  sg-e1395da9

Where $newid is the EC2 instance_id, and sg-e1395da9 the SG group we're adding.

BTW the command is idem-potent, yay!

arod
  • 542
  • 6
  • 19