Finding all Amazon AWS Instances That Do Not Have

2019-03-08 10:49发布

I'm trying to use the Amazon AWS Command Line Tools to find all instances that do not have a specified tag.

Finding all instances WITH a tag is simple enough, e.g.

ec2-describe-instances --filter "tag-key=Name"

But how would I invert that filter to return only the instances that have no tag "Name"?

8条回答
可以哭但决不认输i
2楼-- · 2019-03-08 11:33

You can do that with jmespath (the engine that drives the --query parameter) despite what others say:

aws ec2 describe-instances \
  --query 'Reservations[].Instances[?!not_null(Tags[?Key == `Name`].Value)] | []'

Source: Using Amazon Web Services Command Line Interface (AWS CLI) to Find Instances without a 'Name' Tag.

查看更多
淡お忘
3楼-- · 2019-03-08 11:34

Since --filters parameter doesn't seem to support inverse filtering, here's my solution to this problem using --query parameter:

aws ec2 describe-instances \
--query 'Reservations[].Instances[?!contains(Tags[].Key, `Name`)][].InstanceId'

It looks at an array of tag keys for each instance and filters those instance that don't have Tag 'Name' in the array. Then flattens output to array of instance IDs.

  • Advantage over some previous answers: no need for jq or other command to filter output.
  • Disadvantage over true inverse filter: likely to be much slower over large number of instances.
查看更多
登录 后发表回答