2

I'm trying to do some scripting with the Azure CLI. Say that my query is returning the following:

[
  "a",
  "b",
  "c"
]

I want to use these values in a bash loop. It would be much nicer to get them in the following form:

a
b
c

Is there a way to do that with, ideally, JMESPath query primitives? Otherwise I'll have to use bash commands which leaves a lot to be desired from JMESPath.

s g
  • 5,289
  • 10
  • 49
  • 82

2 Answers2

2

I haven't had much success with JMESPath to query the output. But I have found using jq is a little bit easier to parse the json that is returned.

For example, I need to add internal service endpoints to all the subnets within a particular virtual network. I will pass the json output to a bash array and with a for loop you can execute commands using the json key value pairs.

update_subnet() {
subnet_service_endpoints="Microsoft.EventHub Microsoft.KeyVault Microsoft.ServiceBus Microsoft.Storage"

subnet_json=$(az network vnet subnet list --subscription ${subscription_name} --resource-group ${resource_group} --vnet-name ${virtual_network} --output json)

readarray -t SUBARR < <(echo ${subnet_json} | jq -c '.[]')

for SUBNET in "${SUBARR[@]}"
do
  SUBNET_NAME=$(echo "${SUBNET}" | jq -r .name)
  ADDRESS_PREFIX=$(echo "${SUBNET}" | jq -r .addressPrefix)
  RESOURCE_GROUP=$(echo "${SUBNET}" | jq -r .resourceGroup)

  RESULT=$(az network vnet subnet update --subscription ${subscription_name} --resource-group ${resource_group} --vnet-name ${virtual_network} --name ${SUBNET_NAME} --address-prefixes ${ADDRESS_PREFIX} --service-endpoints ${subnet_service_endpoints})

  if [ "$RESULT"  == "" ]
  then
    echo "Something happened and unable to parse command"
  else
    echo "${RESULT}"
  fi
done

}
  • I've definitely found `jq` to be superior. Unfortunately, because the `az` tools have jmespath built in, it's often preferable to not bring in a new tool unless absolutely necessary – s g Apr 05 '19 at 18:37
1

It seems that you could use --out tsv,

For example, az vm list --out tsv | grep RGD | cut -f8

KBDemo001VM
KBDemo020

More details from https://learn.microsoft.com/en-us/cli/azure/format-output-azure-cli?view=azure-cli-latest#tsv-output-format

Nancy
  • 26,865
  • 3
  • 18
  • 34