amazon-web-servicesaws-clijmespath

Filtering EC2 instances using JMESPath query


This works:

aws ec2 describe-instances \
  --region eu-west-1 \
  --query Reservations[].Instances[].ImageId
[
    "ami-0123456789abcdefg",
    "ami-023456789bcdefghi",
    "ami-03456789cdefghijk"
]

But, when I try to add a filter it doesn't work anymore and returns empty arrays, plus I would only expect one result not many.

aws ec2 describe-instances \
  --region eu-west-1 \
  --query Reservations[].Instances[?ImageId=='"ami-0123456789abcdefg"'].ImageId
[
    [],
    [],
    []
]

What am I doing wrong?


Solution

  • Use backticks (`) instead of double quotes when using strings in the filter expression.

    e.g.:

    aws ec2 describe-instances \
      --query 'Reservations[].Instances[?ImageId==`ami-0123456789abcdefg`].ImageId'
    

    Single quotes can be used, but I would recommend wrapping the entire query in those to keep the shell from interpreting any part of it.
    Backticks are a alternative and allow for more human-readable queries.