joshft91
joshft91

Reputation: 1895

How can I select all elastic IPs that are not assigned to an EC2 instance?

I'm trying to get all Elastic IPs that are not currently assigned to instances.

It's easy to get all of the Elastic IPs using this: aws ec2 describe-addresses

From here, it would be easy to filter out any results that do not have an"AssociationId". However, I'm not sure how to do that using --query.

I know that the --query option uses JMESPath to filter results, but I have no idea how to tell it to return me all results that do not have an AssociationId. Any help?

Thanks.

Upvotes: 13

Views: 9451

Answers (2)

Sachin Yadav
Sachin Yadav

Reputation: 71

ElasticIPs are also attached to NAT Gateways. In that case InstanceID value will be null but AssociationID is the field which will be present there in any scenario. So better to use associationID to be sure that EIP is in use or not.

Upvotes: 6

Anthony Neace
Anthony Neace

Reputation: 26031

You can check the Addresses collection for null values, but instead of AssociationId a better general solution may be better to use InstanceId:

InstanceId -> (string)

The ID of the instance that the address is associated with (if any).

AssociationId -> (string)

The ID representing the association of the address with an instance in a VPC.

Elastic IPs that are not in a VPC do not have the AssociationId property, but elastic IPs in both VPC and EC2 Classic will output InstanceId.

You can alternatively use AssociationId in the same way, if you only care about IPs in a VPC.

Examples:

aws ec2 describe-addresses --query 'Addresses[?InstanceId==null]'

aws ec2 describe-addresses --query 'Addresses[?AssociationId==null]'

Further Reading:

Upvotes: 23

Related Questions