Azure CLI 2.0 jmespath, kubectl queries and tips


I hate how Azure CLI and kubectl do the same thing in slightly different manner, I always forget and mix them up. I’ll just compile this in this post for my future reference (and yours). Folks online also suggest using jq with kubectl a lot. I’ll update this post as time flies.

Azure CLI 2.0

# simple property query
az vm show -g rgname -n vmname --query osProfile.linuxConfiguration.ssh.publicKeys -o json

# multi property query with rename
az vm show -g rgname -n vmname --query '[VMName:name, admin:osProfile.adminUsername]' -o json

# filter array and expand it (arrays support slices like python tuples\lists)
az vm list -g rgname --query "[?storageProfile.osDisk.osType=='Linux'].{Name:name,  admin:osProfile.adminUsername}" --output table

# filter with contains
az vm list -g demo.VMs --show-details --query "[?contains(name, 'Linux') && powerState == 'VM deallocated']".id -o tsv 

# min, max, min_by, max_by, sort_by, sort, reverse
az vm list -g rgname --query "sort_by([].{Name:name, Size:storageProfile.osDisk.diskSizeGb}, &Size)" --output tsv

# pipes (get location for resourceType)
az provider list --query "[?namespace=='Microsoft.Compute'].resourceTypes[].{resourceType:resourceType, locations:locations} | [?resourceType=='virtualMachines'] | [0].locations"

# starts_with\ends_with
az network dns record-set txt show -g myresourcegroup -z '' -n 'mytxtvalues' --query "txtRecords[*].value[?starts_with(@, 'abc')]"

# random query I found online
az vm list-ip-addresses -g rgname --query "[].virtualMachine[].{Name:name, PublicIp:network.publicIpAddresses[0].ipAddress, PrivateIp:network.privateIpAddresses[0]}" -o tsv

Name    PrivateIp    PublicIp
------  -----------  --------------

# to_array, to_string, to_number, length


# get something and output one on line
kubectl get svc -n kube-system --selector app=nginx-ingress -o=jsonpath='{range .items[*]}{}{"\\n"}{end}'

# get pods in weird states
kubectl get pods --field-selector=status.phase!=Running -n kube-system

# get not ready nodes
kubectl get nodes -o jsonpath='{range .items[*]}{.status.conditions[?(@.type=="Ready")].status}{"\\n"}{end}' | grep -P "^((?!^True).)*$"

Useful links:


Happy deploying!

Written on January 26, 2019