Ahoy, There!
This is just one blog post in an ongoing series about fun things you can do with the Kubernetes CLI, kubectl. We have a whole bunch of these over on our Silly Kubectl Tricks page. Also don’t forget to checkout out the video series on YouTube!
kubectl
can pull a lot of data about our deployments and pod. Most of the time, we humans are the recipients of that information, and kubectl
obliges by nicely formatting things in pretty tables.
In my experience, the very next command that I run needs that auto-generated Pod ID, something like kubectl logs
or kubectl exec
. The first couple of times, you’ll use the pasteboard – highlight the pod name with your mouse, Cmd-C
, and you’re off to the races. By the third, fourth, or fiftieth time, however, you’ll be wishing for a better way.
This is UNIX, right? World-famous for its text processing capabilities? We got this covered.
$ kubectl get pods
$ kubectl get pods | awk '{print $1}'
$ kubectl get pods | awk '{print $1}' | grep -v ^NAME
Well, it does work, even if it is a bit awkward, and a lot to type.
kubectl
has lots of different output formats at its disposal; the default one just happens to be such a good fit for human eyes that we don’t always go looking for others. We can change the output format via the -o
flag. For example, we can dump all of the pods in JSON format, and then use jq
to parse through it:
$ kubectl get pods -o json | \
jq -r '.items[0].metadata.name'
frontend-64d9f4f776-9fzp8
What happens if we don’t have jq
available to us? This may surprise you, what with this being a blog post about kubectl
tricks and all, but kubectl
can do this natively…
It’s called JSON Path, and it essentially lets you embed simple jq
scripts into your kubectl
call, directly:
$ kubectl get pods -o jsonpath='{.items[0].metadata.name}'
frontend-64d9f4f776-9fzp8
(Just remember to enclose the variable reference in balanced curly braces.)
JSON Path has its fair share of fanciness, including filters. For example, if you have a pod with lots of constituent containers, you can extract information about a subset like this:
$ kubectl get pods -o jsonpath='{.items[0].spec.containers[?(@.image == "redis")].name}'
kv-store
session-cache
Here we’re identifying which containers in our pod are running the upstream redis
image. Neat!