AWS CLI provides a way for filtering by tag-key and tag-value in the following ways:
aws ec2 describe-instances --filters Name=tag-key,Values=my_tag
aws ec2 describe-instances --filters Name=tag-value,Values=my_tag_value
aws ec2 describe-instances --filters Name=tag:my_tag,Values=my_tag_value
but when tag contains multiple values, e.g. my_tag: my_value1, my_value2, my_value3 it doesn't work. When using any of the previous commands, it returns only those instances which contains tag with exactly this value. All other cases where the tag contains value along with other values are ignored.
How to achieve filtering like 'tag contains this value' instead of 'tag is exactly this value'?
P.C. I'll be using this approach in java application using aws-sdk, so I'm interested in aws-sdk api solution; I definitely don't want to filter a set of instances on my server-side.
CodePudding user response:
You can filter tag values based on wildcards (either * or ? for multi or single character match respectively) or by listing them as comma separated values. So if I have three instances with a tag "t1" and different possible values across several instances, I can select them all with the following command:
aws ec2 describe-instances --filters Name=tag:t1,Values=*
You can also select subsets by using the wildcards or comma separated lists. Some examples are below, and the AWS reference page is located here for further information.
Match all values for the t1 tag that start with "myval" (Note the --query parameter is used in this example to just select the instance id, so we can quickly compare the results without scrolling all the JSON output):
$ aws ec2 describe-instances --filters Name=tag:t1,Values=myval* --query "Reservations[*].Instances[*].InstanceId" --output text
Match a comma separated list of values:
$ aws ec2 describe-instances --filters Name=tag:t1,Values=t1val1,t1val2
Match a single character wildcard:
$ aws ec2 describe-instances --filters Name=tag:t1,Values=t1val?