AZ CLI and JMESPath queries

Very often when scipting the infrastructure in Azure, you will have to deal with [JMES Paths]https://docs.microsoft.com/en-us/cli/azure/query-azure-cli?tabs=concepts%2Cbash).
As a developer, I mostly find complex scripts spaghetti-like. And honestly making queries by JMES Paths makes me very often crazy. II don’t know how about you, but I always miss some ‘ or similar somewhere and spend unnecessarily a lot of time waiting on pipeline execution, to look up the error, understand the error and finally fix it.

Here is an example:

ERROR: argument --query: invalid jmespath_type value: '[?name==mykeyvault-test123] | length(@)

aaaaaaaaaaaa

If you want to create the service (keyvault in this case) you will use a script like this one:

$vaultname = 'mykeyvault123'

az keyvault create --location $(location) -n $vaultname --resource-group $(rg)

Please note that argument -n, is the variable $vaultname without ‘.

If you use JMES path, you would probably write something like this:

$vaultname = 'mykeyvault123'

$len = az keyvault list --query "[?name== $vaultname] | length(@)"

Unfortunately, this will fail. The reason for this is that JMES Path is the parser that executes behind the pipeline parser that executes behind the PowerShell parser (in this case). All these parser output concatenation makes scripting not very brain-friendly.

Here is one example that demonstrates how to check if the key vault exists and how to create it if it doesn’t. Focus on using ‘ in the JMES query.

$vaultname = 'mykeyvault123'

$len = az keyvault list --query "[?name== '$vaultname'] | length(@)"

if ( $len = 0 )
{
     az keyvault create --location $(location) -n $vaultname --resource-group $(rg)
}

Hope this save you some minutes or even hours of searching for mistakes, that you didn;t make.


comments powered by Disqus