List security groups associated with EC2 instances
I'm into writing one-liners using join
, aws
and jq
commands
in order to briefly check some information without logging in management console.
The following one-liner prints security groups with EC2 instance ID and tag Name. It's helpful to glance security group association.
join -a1 <(aws ec2 describe-instances --filter "Name=instance-state-name,Values=running"| \
jq -r '.Reservations[].Instances[]|. as $it|
{x: $it.InstanceId, a:.SecurityGroups[].GroupId}|
[.a, .x, ($it.Tags|select(.!=null)[]|select(.Key=="Name").Value)]|
@tsv'|sort) \
<(aws ec2 describe-security-groups | \
jq -r '.SecurityGroups[]|. as $sg|.IpPermissions[]|
[$sg.GroupId, .FromPort, .ToPort, .IpProtocol,
.UserIdGroupPairs[].GroupId, .IpRanges[].CidrIp,
($sg.Tags|select(.!=null)[]|select(.Key=="Name").Value)]|
@tsv'|sort) \
| sort -k2