6

I'm looking for syntax like:

aws ec2 describe-security-groups --instance-id i-0xyz

however, the above sub-command doesn't support --instance-id parameter.

I've checked and there are --filters and --query parameters, but I'm not sure about the syntax.

What would be the easiest way to display the description of the security group of the instance?

Chaminda Bandara
  • 157
  • 2
  • 12
kenorb
  • 7,841
  • 12
  • 40
  • 77

5 Answers5

5

The following one-liner in shell works for me:

aws ec2 describe-security-groups --group-ids $(aws ec2 describe-instances --instance-id $id --query "Reservations[].Instances[].SecurityGroups[].GroupId[]" --output text) --output text

Where $id is my instance-id.

kenorb
  • 7,841
  • 12
  • 40
  • 77
4

You can use aws ec2 describe-instances instead, you can specify the id --instance-ids <value> and it will output the security group.

kenorb
  • 7,841
  • 12
  • 40
  • 77
0

Even better check this out:

aws ec2 describe-instances --output=json | jq '.Reservations[] | .Instances[] | {PrivateAddress: .PrivateIpAddress, Tags: .Tags, KeyName: .KeyName, Tags: .Tags, RunningState: .State, InstanceId: .InstanceId, SecurityGroups: .SecurityGroups}'

You don't need to know anything this way ... but you need to install jq, to chomp the JSON o/p just right.

A lot of the elements there could be removed I guess ... tags, key names, running state, etc.

CODE-REaD
  • 103
  • 4
  • This looks promising, but for me it yields only parse error: Invalid numeric literal at line 1, column 13. I suspect there is some "unanticipated" line in my cli output. – CODE-REaD Dec 20 '21 at 22:24
  • (I amend my comment, above): I had configured my .aws/config file to output text rather than the default JSON. So in my case, using --output=json on the command line caused the prescribed invocation to operate correctly. – CODE-REaD Dec 21 '21 at 19:03
0

If you want to run this on an EC2 instance and find out its own security groups, you can do:

id=$(wget -q -O - http://169.254.169.254/latest/meta-data/instance-id)

for sg in $(aws ec2 describe-instances --instance-id $id
--query "Reservations[].Instances[].SecurityGroups[].GroupId[]"
--output text) do echo aws ec2 describe-security-groups --group-id $sg --output text done

Pierre D
  • 101
  • 1
0

you can use

aws ec2 describe-instances --instance-ids (your Instance id) --query "Reservations[].Instances[].SecurityGroups[].GroupId[]" --output text

replace

(your instance id)
with the specific instance id you are looking for.