Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

aws ec2 describe-instances: how to filter *out* spot instances?

I can list all my spot instances by issuing the following CLI command:

aws ec2 describe-instances --filter Name="instance-lifecycle",Values="spot"

But how can I show all my not spot instances? None of these work:

aws ec2 describe-instances --filter Name="instance-lifecycle",Values=""
aws ec2 describe-instances --filter Name="instance-lifecycle",Values="?"

(the instance-lifecycle is empty / null for non-spot instances, similarly for spot-instance-request-id)

like image 730
Jxtps Avatar asked Sep 13 '17 16:09

Jxtps


2 Answers

AWS CLI and console are not working for filtering instance-lifecycle "normal".

So I've use jq tool instead of '--filter Key=instance-lifecycle,Values=scheduled'

aws ec2 describe-instances --filter Name="instance-state-code",Values="16" \
| jq '.Reservations[]?.Instances[]? | select(.InstanceLifecycle == null)| .InstanceId' -r
like image 151
Kwanghee Park Avatar answered Sep 19 '22 21:09

Kwanghee Park


It seems you can do this via the --query option.

I've struggled to find good documentation on the option itself but I managed to come across the fact that you can pass filters inside it.

For example these 2 commands will return the same:

aws ec2 describe-instances --filters "[{\"Name\": \"tag:role\", \"Values\": [\"web\"]}, {\"Name\":\"instance-state-name\", \"Values\": [\"running\"]}]" --query='Reservations[*].Instances[*].[LaunchTime,PrivateIpAddress][]'

aws ec2 describe-instances --filters "[{\"Name\": \"tag:role\", \"Values\": [\"web\"]}]" --query='Reservations[*].Instances[?InstanceStateName=="running"].[LaunchTime,PrivateIpAddress][]'

What this also allows us to do is filter items in the instances output which do not have a specified tag (e.g. "Normal" instances do not have a "InstanceLifecycle" attribute so return null):

aws ec2 describe-instances --filters "[{\"Name\": \"tag:role\", \"Values\": [\"web\"]}, {\"Name\":\"instance-state-name\", \"Values\": [\"running\"]}]" --query='Reservations[*].Instances[?!InstanceLifecycle].[LaunchTime,PrivateIpAddress][]'

Note Instances[?!InstanceLifecycle] in the query.

like image 34
Grant Anderson Avatar answered Sep 22 '22 21:09

Grant Anderson