August 26, 2020
Combine kubectl and JSONPath to read data from a Kubernetes cluster
To customize how data about cluster objects is presented on the terminal, its possible to use JSONPath syntax. Keep in mind that, under the hood, Kubernetes’ API already sends and receives data in JSON format (the YAMLs we’re used to see are an abstraction to ease reading and editing).
Since data hierarchy on the YAML representation may be a bit off, start by getting a pure JSON version of the data you want to filter.
In the following examples, let’s use a specific deployment.
kubectl -n <my_namespace> get deploy/<my_deployment> -o json
Get only the deployment name.
kubectl -n <my_namespace> get deploy/<my_deployment> -o jsonpath='{.metadata.name}'
range
is one of the improvements to JSONPath available here. It iterates over JSON lists and can be paired with @
to make references to each item.
Using both, you can, for instance, print image names for all containers created by a deployment (with line breaks).
kubectl -n <my_namespace> get deploy/<my_deployment> -o jsonpath='{range .spec.template.spec.containers[*]}{@.image}{"\n"}{end}'
A good use case for JSONPath is to list annotations for every deployment in a cluster. Tools like Velero depend on the proper configuration of annotations to do volume backups, so it’s convenient to have a consolidated output.
The following command prints namespace, name and template annotations for every deployment. Additionally, it pipes the list to grep
so we can have color highlights.
kubectl get -A deployments -o jsonpath='{range .items[*]}{@.metadata.namespace}{" / "}{@.metadata.name}{"\n"}{@.spec.template.metadata.annotations}{"\n"}{"\n"}{end}' | grep --color "backup.velero.io/backup-volumes\|$"
Note: grep
is also matching line endings to ensure all lines are printed.