Search code examples
amazon-web-servicescommand-line-interfaceamazon-vpc

aws cli: how can use aws ec2 describe-network-interfaces to list only network interfaces bound to EC2 instances?


I want to list all the network interfaces that are assigned to EC2 instances only, filtering out ENI assigned to things like : SageMaker Studio Domains, EFS mount targets, Route53 Resolver, Transit Gateway Attachments, VPC Endpoints vpce, NAT Gateways, SageMaker Notebook Instances

aws --output json ec2  describe-network-interfaces

returns ENIs for EC2 instances, but there are also other ENIs there (for EFS, etc). How can I filter them out?


Solution

  • The entries for ENIs assigned to EC2 instances will have the Attachment.InstanceId set, for other types of ENIs this attribute will be missing.

    The AWS CLI allows for server side filtering and client side filtering. Unfortunately, although there is a filter attachment.instance-id there is no way to express "any where this is not null`, it only allows for exact matches as far as I know.

    But you can use client-side filtering (--query xxxx) to remove all the returned NetworkInterfaces where the Attachment.InstanceId is null:

    aws  ec2  describe-network-interfaces --query "NetworkInterfaces[?not_null(Attachment.InstanceId)]"
    

    This returns only those ENIs associated with an EC2 instance.