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?
We can start by doing
Which gives us the current security group. For example:
Then we can build upon the previous answer and write:
Or in one line:
Where $newid is the EC2 instance_id, and
sg-e1395da9
the SG group we're adding.BTW the command is idem-potent, yay!