So I want to clean up Elastic Network Interfaces (ENIs) that were created for testing and no longer needed, and I want to use AWS CLI to do that.

For me, I know that all unused ENIs will have their status as “available”. So I will find all those ENIs and will delete them.

➜ aws ec2 describe-network-interfaces --filters Name=status,Values=available \
--query 'NetworkInterfaces[].{NetworkInterfaceId:NetworkInterfaceId,Description:Description}'
[
    {
        "NetworkInterfaceId": "eni-0dc616df583312345",
        "Description": "2nd nic in 2b az"
    },
    {
        "NetworkInterfaceId": "eni-0bf98b53cf1b12345",
        "Description": "2nd nic"
    },
    {
        "NetworkInterfaceId": "eni-034bcff8ceef12345",
        "Description": "test-eni"
    },
    {
        "NetworkInterfaceId": "eni-09adbc3a20c912345",
        "Description": "Test 2nd eni on custom subnet 2a AZ"
    }
]

Next, I need to feed each of the values of “NetworkInterfaceId” to the delete command aws ec2 delete-network-interface, which takes only 1 NetworkInterfaceId at a time.

What is the best way or a way to approach it? Well, I would just try to flatten the NetworkInterfaceId values to a list of all interfaces, then will use bash for loop to go through each one of them.

➜ aws ec2 describe-network-interfaces --filters Name=status,Values=available \
    --query 'NetworkInterfaces[].NetworkInterfaceId' --output text
eni-09adbc3a20c912345   eni-034bcff8ceef12345   eni-0bf98b53cf1b12345   eni-0dc616df583312345

Here is a quick test to add bash for loop:

➜ for eni in $(aws ec2 describe-network-interfaces --filters Name=status,Values=available --query 'NetworkInterfaces[].NetworkInterfaceId' --output text); do echo "delete ${eni}"; done
delete eni-09adbc3a20c912345
delete eni-034bcff8ceef12345
delete eni-0bf98b53cf1b12345
delete eni-0dc616df583312345

The moment of truth, let’s execute the real deletion command:

➜ for eni in $(aws ec2 describe-network-interfaces --filters Name=status,Values=available --query 'NetworkInterfaces[].NetworkInterfaceId' --output text); do aws ec2 delete-network-interface --network-interface-id ${eni}; done

Finally, let’s verify if there exist any “available” ENIs:

➜ aws ec2 describe-network-interfaces --filters Name=status,Values=available \
--query 'NetworkInterfaces[].NetworkInterfaceId' --output text

References: