Azure CLI 2.0 jmespath, kubectl queries and tips

Howdy,

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 'mydomain.com' -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
------  -----------  --------------
vm001   192.168.0.4  52.170.213.177
vm002   192.168.0.5

# to_array, to_string, to_number, length

kubectl

# get something and output one on line
kubectl get svc -n kube-system --selector app=nginx-ingress -o=jsonpath='{range .items[*]}{.metadata.name}{"\\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:

  1. http://jmespath.org/specification.html#built-in-functions
  2. https://azurecitadel.com/prereqs/cli/cli-3-jmespath/
  3. https://kubernetes.io/docs/reference/kubectl/cheatsheet/#viewing-finding-resources

Happy deploying!

Written on January 26, 2019