AWS CLI to find EC2's security groups id and subnet id

Viewed 21

Is there a way to use AWS CLI to find EC2's security groups id and subnet id of a particular instance?

I.e., I want to programmatically find this, and its subnet id

enter image description here

1 Answers

You can use the AWS Command-Line Interface (CLI):

aws ec2 describe-instances

This will return information about all instances.

To obtain information about a specific instance, you can use:

aws ec2 describe-instances --instance-ids i-xxx

To obtain specific parameters, you could use:

aws ec2 describe-instances --query 'Reservations[].Instances[].[InstanceId,NetworkInterfaces[].Groups[].GroupId,NetworkInterfaces[].SubnetId]'

Please note that an Amazon EC2 instance can have multiple Network Interfaces and multiple Security Groups, so the formatting will be a challenge if you wish to capture the output and use it in some way.

Alternatively, you could use an AWS SDK to programmatically request the information (eg using Java or Python).

Related