Silly Kubectl Trick #8: Data Extraction With JSON Path
You can change the output format via the -o flag, and then use jq to parse through it.
Join the DZone community and get the full member experience.Join For Free
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.
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:
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:
(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:
Here we're identifying which containers in our pod are running the upstream
redis image. Neat!
Published at DZone with permission of . See the original article here.
Opinions expressed by DZone contributors are their own.