Filtering AWS SQS Tags using JQ



  • I'm having doubts when trying to run a query with JQ. I have an SQS queue with Tags applied and when I run

    aws sqs list-queue-tags --region sa-east-1 --queue-url --output json | jq

    returns the output:

    {
      "Tags": {
        "owner": "foo",
        "Name": "bar-queue"
      }
    }
    

    So...I just filter using like this:

    aws sqs list-queue-tags --region sa-east-1 --queue-url --output json | jq '.Tags[] | [.Name]'

    or

    aws sqs list-queue-tags --region sa-east-1 --queue-url --output json | jq '.Tags[].Name'

    and other methods without success, always output: jq: error (at :6): Cannot index string with string "Name"

    Maybe I'm having a noobie hahaha, but someone can help me?



  • Take heart, I've been struggling with JMESPath query expressions for the past couple of years! It's been a long time getting used to them.

    In your example output, Tags is a JSON object rather than a list, so the [] in your JMESPath expression is causing the error. Try this as your jq command:

    jq '.Tags.Name'
    

    You'll get:

    "bar-queue"
    

    You can use the -r option to jq to get the output without quotes.

    However I think you can do better by having the aws command do this filtering for you. Try the --query option:

    aws sqs list-queue-tags --region sa-east-1 --queue-url  --query 'Tags.Name'
    

    Yes, the expression for the aws command doesn't have the leading .. If you don't want the quotes around the output, add the option --output text.


    Edited to add these notes about JMESPath expressions for jq vs. aws:

    The leading . character isn't the only difference between expressions that jq likes and the ones the aws command likes. I don't have an exhaustive list, but I have needed to use different quotes around path names for one program than I used for the other.

    There are pretty good tutorials on query expressions for each of these programs:

    • jq : https://stedolan.github.io/jq/tutorial/
    • aws : https://docs.aws.amazon.com/cli/latest/userguide/cli-usage-filter.html

    And a website that's useful for interactively trying out expressions, once you've figured out how the site works: https://jmespath.org . It includes a link to another, more general tutorial.



Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2