Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

kubectl Output: jsonpath, custom-columns, and the Debugging Commands Worth Knowing

jsonpath for one value in a script, custom-columns for tables people read, and kubectl debug when the container has no shell. Includes the three quoting layers that break jsonpath.

~4 min readKubernetes
#Kubernetes#kubectl#CLI#Debugging
3D illustration of a terminal panel extracting paths from nested JSON blocks into a table beside a probe device

Quick Summary

kubectl output is JSON under the hood, and three output modes read it without a query language: jsonpath (Go templates with a path syntax), custom-columns (a table definition), and go-template (full Go templating). They are the difference between reading twenty pods' statuses by hand and getting one line per pod that a script can consume.

The syntax that trips people up: paths start at the object root (.items[*].metadata.name), [*] flattens arrays, {"\n"} and {"\t"} are the separators inside {range} loops, and quoting matters twice — once for the shell, once for kubectl. Filters use ?(@.field=="value"), and -o jsonpath prints nothing at all when a path does not exist, which is why custom-columns is safer for tables full of optional fields.

Debugging is the other half of this page: kubectl debug for an ephemeral container in a running pod or a copy of it, kubectl events for a sorted view of what happened, kubectl auth can-i for permission questions, and --sort-by plus -w for watching a rollout without a dashboard.

Basic Syntax & Core Signatures

bash
# jsonpath: table of name and phase kubectl get pods -o jsonpath='{range .items[*]}{.metadata.name}{"\t"}{.status.phase}{"\n"}{end}' # jsonpath: one field, no loop kubectl get pod api-0 -o jsonpath='{.status.containerStatuses[0].restartCount}' kubectl get svc api -o jsonpath='{.spec.clusterIP}{"\n"}' # jsonpath: filter with an expression kubectl get pods -o jsonpath=\ '{.items[?(@.status.phase=="Running")].metadata.name}' # jsonpath: images of every container in every pod, one per line kubectl get pods -o jsonpath='{range .items[*]}{.metadata.name}{": "}{.spec.containers[*].image}{"\n"}{end}' # negative index and last element kubectl get events -o jsonpath='{.items[-1:].message}{"\n"}'
bash
# custom-columns: a named table, blanks for missing paths kubectl get pods -o custom-columns=\ NAME:.metadata.name,\ NODE:.spec.nodeName,\ READY:.status.containerStatuses[*].ready,\ RESTARTS:.status.containerStatuses[*].restartCount,\ CPU_REQ:.spec.containers[*].resources.requests.cpu kubectl get nodes -o custom-columns=\ NAME:.metadata.name,ZONE:.metadata.labels.topology\.kubernetes\.io/zone,CPU:.status.allocatable.cpu
bash
kubectl get pods --sort-by='.status.containerStatuses[0].restartCount' kubectl get pods --field-selector status.phase=Failed -A kubectl get pods -w -o custom-columns=NAME:.metadata.name,PHASE:.status.phase kubectl auth can-i create pods --as=system:serviceaccount:shop:api kubectl explain deployment.spec.strategy --recursive | head -20

Key Comparison Table

Output modeSyntaxBest forMissing field
jsonpath{.a.b[*].c}Scripts, single valuesPrints nothing
custom-columnsNAME:.a.bHuman tablesPrints <none>
go-template{{range .items}}Complex logic, conditionalsindex errors
json + jqJSON pipeAd-hoc explorationjq null
widebuilt-inQuick node/IP viewn/a
ExpressionMeaning
.items[*].metadata.nameEvery name in the list
{range .items[*]}…{end}Loop with explicit separators
{?(@.status.phase=="Running")}Filter on the current node
{.metadata.labels.topology\.kubernetes\.io/zone}Escaped dots in a label key
{.items[-1:]}Last element
{.spec.containers[*].name}Flattened list, space-separated by default
Debug commandPurpose
kubectl debug -it pod/x --image=busyboxEphemeral container in a running pod
kubectl debug pod/x --copy-to=x-dbg --share-processesCopy of the pod spec, original untouched
kubectl debug node/n1 -it --image=busyboxHost namespace shell via a privileged pod
kubectl events --for pod/x --watchEvents for one object, sorted
kubectl auth can-i --list -n shopWhat the current identity may do

Practical Edge Cases & Deep Dives

1. Quoting: three layers, and where it breaks

bash
# Works in bash: single quotes protect the braces and quotes kubectl get pods -o jsonpath='{range .items[*]}{.metadata.name}{"\t"}{.status.phase}{"\n"}{end}' # Breaks: double quotes let bash expand {"\t"} into an empty string kubectl get pods -o jsonpath="{range .items[*]}{.metadata.name}{"\t"}{"\n"}{end}" # -> every name concatenated on one line

Inside a shell script that already uses double quotes, the reliable form is to put the jsonpath in a variable with single quotes, or to escape \t as \\t inside double quotes. The same applies to label keys containing dots: topology.kubernetes.io/zone must be escaped as topology\.kubernetes\.io/zone, and the backslash survives the shell only inside single quotes.

2. jsonpath versus custom-columns for optional fields

Container statuses are absent while a pod is Pending, and resources.requests is absent when a container declares none. jsonpath silently prints an empty string, so a table built with jsonpath has columns silently shifting. custom-columns prints <none> and keeps position:

bash
kubectl get pods -o custom-columns=\ NAME:.metadata.name,CPU:.spec.containers[0].resources.requests.cpu # NAME CPU # api-0 500m # api-1 <none>

For anything a human reads, custom-columns; for anything a script parses, jsonpath with -o json and jq when the structure is nested.

3. Sorting, filtering, and watching without a UI

--sort-by takes a jsonpath and sorts client-side; --field-selector filters server-side and supports a small set of fields (metadata.name, metadata.namespace, status.phase, spec.nodeName, involvedObject.* for events). Labels filter with -l, which is the efficient one — labels are indexed in etcd, arbitrary jsonpath fields are not.

bash
kubectl get pods -A --field-selector=status.phase=Failed --sort-by=.metadata.creationTimestamp kubectl get pods -l app=api,version!=v1 -o custom-columns=NAME:.metadata.name,V:.metadata.labels.version

4. kubectl debug: three modes, three meanings

bash
# 1. Ephemeral container in the live pod: shares the network namespace kubectl debug -it api-0 --image=nicolaka/netshoot --target=api -- ss -ltnp # 2. A copy with a modified spec: leaves the original running kubectl debug api-0 --copy-to=api-dbg --container=api --image=registry.example.com/shop/api:debug \ -- sh -c 'sleep 3600' # 3. A pod in the host namespaces of a node kubectl debug node/node-7 -it --image=busybox

The first mode requires the container runtime and the API server to allow ephemeral containers, needs pods/ephemeralcontainers permission, and cannot be added to a pod whose spec is immutable in other ways. The second is the right tool when the image has no shell, because you can substitute an image while keeping volumes and env. The third mounts the host filesystem at /host and is the fastest way to inspect a node whose kubelet is misbehaving.

5. kubectl auth can-i and the --as trick

bash
kubectl auth can-i get secrets -n shop kubectl auth can-i --list --as=system:serviceaccount:shop:api -n shop # Resources Non-Resource URLs Resource Names Verbs # pods [] [] [get list watch] kubectl auth can-i create pods --as=system:serviceaccount:shop:api -n kube-system # no

--as requires the impersonate verb on your own identity, which cluster admins have and most users do not. When it is refused, the answer is not about the target identity at all — it is about your permission to ask.

Common Runtime & Configuration Mistakes

SymptomCauseFix
jsonpath prints one concatenated lineShell ate \t/\nSingle-quote the expression
error: unexpected end of JSON inputPath past a missing array elementCheck with -o json, use custom-columns
Label path returns nothingDots in the key not escapedtopology\.kubernetes\.io/zone
Columns shift between rowsOptional field empty with jsonpathcustom-columns
--field-selector rejects a fieldOnly a fixed field set is supportedFilter client-side or by label
Sorting looks wrongString sort on a numeric fieldParse with jq -s 'sort_by(.x)'
Ephemeral container refusedMissing pods/ephemeralcontainers RBACGrant the verb, or use --copy-to
debug copy fails on a StatefulSet podVolumes already boundDebug with --copy-to and adjusted mounts
--as returns ForbiddenNo impersonate verbAsk an admin, or test with a Role in a scratch namespace
-o jsonpath too complex to readWrong tooljq on -o json

The practical rule: custom-columns for what a person reads on a terminal, jsonpath for a single value in a script, and -o json | jq the moment the path needs conditionals. For anything that is not about output at all — a container with no shell, a node that is misbehaving — kubectl debug and kubectl events replace guesses with evidence.

Try matching browser tools

All tools

Small utilities that fit Kubernetes work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Kubernetes guides

More in Kubernetes

All Kubernetes guides

The guides filed next to this one in Kubernetes, in library order.