Search code examples
bashazure-clijmespath

How to filter Azure CLI outputs by value using JMESPath queries on Bash when keys contain hyphens/dashes?


The az keyvault secret list --vault-name "lofa" results in a list similar to what is below (but has way more elements of each type):

[
  {
    "attributes": { ... },
    "id": "https://lofa.vault.azure.net/secrets/conn-string",
    "tags": {
      "file-encoding": "utf-8"
    }
  },
  {
    "attributes": { ... },
    "id": "https://lofa.vault.azure.net/secrets/a-password",
    "tags": null
  },
  {
    "attributes": { ... },
    "id": "https://lofa.vault.azure.net/secrets/another-password",
    "tags": {
      "testThis": "miez",
      "what": "else"
    }
  }
]

Tried to filter the "easy" targets first (i.e., JSON objects where the keys contain no hyphens), and it worked as expected:

$ az keyvault secret list --vault-name "lofa" --query "[? tags.testThis=='vmi']"

The same didn't work for file-encoding keys (resulting in invalid jmespath_type value):

$ az keyvault secret list --vault-name "lofa" --query "[?tags.file-encoding=='utf-8']"

So tried single quotes next, but no joy:

$ az keyvault secret list --vault-name "lofa" --query "[?tags.'file-encoding'=='utf-8']"

Solution

  • And if you do want a solution that does not forces you to escape any quotes, you can use:

    • simple quotes for your shell script parameters
      az keyvault secret list --vault-name 'lofa' --query '[]'
      
    • double quotes for your key, since it contains a dash
      az keyvault secret list --vault-name 'lofa' --query '[?tags."file-encoding"]'
      
    • backticks for your literal, utf-8
      az keyvault secret list --vault-name 'lofa' --query '[?tags."file-encoding"==`utf-8`]'