Day 1: kubectl for Advanced Users
Goal: Answer questions to the cluster in a single line: look up fields with
explain, build your own tables withcustom-columns, filter precisely with JSONPath, jq and field selectors, and wait correctly withwait· Duration: approx. 75 min · Prerequisite: Day 0
Briefing
kubectl getdelivers more than the default table. Every object is a JSON document, and kubectl can pull exactly the fields you need out of it. Once you master this, you need no additional tool for half of the everyday questions.- Three output forms, three strengths: custom-columns for tables meant for reading, JSONPath for single values and simple filters directly in kubectl, jq for everything that needs logic.
- Plus two helpers that are often used wrongly: field
selectors filter on the server, but only a few fields;
kubectl waitwaits for a condition, but not always for the one you mean.
| Question | Tool |
|---|---|
| What does this field mean, which type does it have? | kubectl explain |
| Which Pod runs on which node with which image? | -o custom-columns |
| Which container runs privileged? | -o jsonpath with a filter |
| Which Pods have no limits? | -o json and jq |
| What just happened? | get events --sort-by |
| When is the rollout really finished? | kubectl wait --for=jsonpath |
Drill 1: Looking Up Fields
kubectl explain reads the description directly from the
API server’s OpenAPI schema, so it always matches the cluster
version:
kubectl explain deployment.spec.strategy.rollingUpdate.maxSurge | head -12Expected:
GROUP: apps
KIND: Deployment
VERSION: v1
FIELD: maxSurge <IntOrString>
DESCRIPTION:
The maximum number of pods that can be scheduled above the desired number of
pods. Value can be an absolute number (ex: 5) or a percentage of desired
pods (ex: 10%). This can not be 0 if MaxUnavailable is 0. Absolute number is
calculated from percentage by rounding up. Defaults to 25%. Example: when
You find the path to a field with
kubectl explain deployment --recursive | less: it shows the
whole tree without descriptions.
Save your progress? Sign up for free
Drill 2: Your Own Tables
Which Pod of the shop runs where, with which image? The default
output does not show this in one table, custom-columns
does. Each column is NAME:JSON-path:
kubectl get pods -A -l 'app in (web,api,cache,packer)' \
-o custom-columns=NS:.metadata.namespace,POD:.metadata.name,KNOTEN:.spec.nodeName,IMAGE:.spec.containers[0].imageExpected (Pod names and distribution will differ for you):
NS POD KNOTEN IMAGE
laden api-7d5f77c79b-725kc werkzeuge-worker2 traefik/whoami:v1.11.0
laden api-7d5f77c79b-gjmtc werkzeuge-worker traefik/whoami:v1.11.0
laden cache-55b4555575-xkp72 werkzeuge-worker2 redis:8.2.3-alpine
laden web-67649cfddb-6d48k werkzeuge-worker2 nginx:1.30.7-alpine
laden web-67649cfddb-fzrd6 werkzeuge-worker2 nginx:1.30.7-alpine
laden web-67649cfddb-tggck werkzeuge-worker nginx:1.30.7-alpine
lager packer-68485bc749-ksh4x werkzeuge-worker2 busybox:1.37.0
Five of seven Pods on werkzeuge-worker2: the scheduler
distributes by free resources, not evenly. If you want resilience, you
need topology spread constraints or anti-affinity.
Save your progress? Sign up for free
Drill 3: JSONPath with a Filter
Which Pods run privileged? JSONPath can filter:
?(@.feld==wert). range … end prints each match
on its own line:
kubectl get pods -A -o jsonpath='{range .items[?(@.spec.containers[0].securityContext.privileged==true)]}{.metadata.namespace}/{.metadata.name}{"\n"}{end}'Expected (names will differ for you):
kube-system/kube-proxy-4dw4k
kube-system/kube-proxy-t4qqv
kube-system/kube-proxy-vqhhr
lager/packer-68485bc749-ksh4x
Besides packer, the three kube-proxy Pods
also run privileged. For kube-proxy, this is intended: it writes
iptables rules on the node. What matters is that you know it before a
scanner reports it to you as a finding.
Caution: The filter only checks
containers[0], the first container. A privileged sidecar in second place slips through. JSONPath in kubectl cannot express “any container”; that is what jq is for (Drill 4).
Save your progress? Sign up for free
Drill 4: jq for Everything with Logic
Which Pods in laden (shop) and lager
(warehouse) have at least one container without limits?
any() checks all containers:
kubectl get pods -A -o json | jq -r '.items[]
| select(.metadata.namespace=="laden" or .metadata.namespace=="lager")
| select(any(.spec.containers[]; .resources.limits == null))
| "\(.metadata.namespace)/\(.metadata.name)"'Expected:
laden/api-7d5f77c79b-725kc
laden/api-7d5f77c79b-gjmtc
laden/cache-55b4555575-xkp72
laden/werkbank
lager/packer-68485bc749-ksh4x
Only web has limits, as planned on Day 0. That the
werkbank (workbench) shows up as well is correct:
kubectl run sets no limits.
Rule of thumb: JSONPath as long as a single value or a simple filter is enough; jq as soon as “any”, “all”, grouping or counting comes into play.
Save your progress? Sign up for free
Drill 5: What Just Happened?
Events come unsorted. With --sort-by, the newest are at
the bottom, and tail shows them:
kubectl -n laden get events --sort-by=.lastTimestamp | tail -4 | cut -c1-150Expected (shortened):
2m55s Normal Scheduled pod/werkbank Successfully assigned laden/werkbank to werkzeuge-worker2
2m54s Normal Pulled pod/werkbank Container image "busybox:1.37.0" already present on machine and can be accesse
2m53s Normal Created pod/werkbank Container created
2m53s Normal Started pod/werkbank Container started
By default, events live for only one hour. If you want to know later what happened, you have to collect them, for example with an event exporter (profile in the Tool Finder, Appendix C).
Save your progress? Sign up for free
Drill 6: Field Selectors
Field selectors filter on the API server instead of in the client. In large clusters, this saves bandwidth, and they work with every output form:
kubectl get pods -A --field-selector=status.phase!=Running,status.phase!=Succeeded
kubectl get pods -A --field-selector spec.nodeName=werkzeuge-worker -o name | head -5
kubectl -n lager get jobs --field-selector status.phase=SucceededExpected:
No resources found
pod/cilium-envoy-rq68s
pod/cilium-n72fp
pod/coredns-559f6c778d-8mnjb
pod/coredns-559f6c778d-rtbz9
pod/hubble-relay-66867f6cb8-jh487
Error from server (BadRequest): Unable to find "batch/v1, Resource=jobs" that match label selector "", field selector "status.phase=Succeeded": field label "status.phase" not supported for Job
- First line: no Pod is in a state other than
RunningorSucceeded, so the cluster is healthy. This line is worth making a habit after every change. - Second: everything running on a node, for example before maintenance.
- Third: field selectors only know a few fields per resource (for
Pods, among others,
status.phase,spec.nodeName,metadata.name). For everything else: JSONPath or jq.
Save your progress? Sign up for free
Drill 7: Waiting Correctly
Scripts and CI pipelines have to wait until something is finished.
kubectl wait does that, but the obvious condition is
deceptive:
kubectl -n laden scale deploy/web --replicas=4
time kubectl -n laden wait --for=condition=Available deploy/web --timeout=60s
kubectl -n laden wait --for=jsonpath='{.status.readyReplicas}'=4 deploy/web --timeout=60s
kubectl -n laden scale deploy/web --replicas=3Expected:
deployment.apps/web scaled
deployment.apps/web condition met
real 0m0.465s
deployment.apps/web condition met
deployment.apps/web scaled
Half a second: the first wait returned immediately,
although the fourth Pod was not even running yet. Available
means “enough Pods for minimum availability”, and with three Pods that
was long since fulfilled. The second wait checks exactly
what is meant: four ready replicas. For rollouts,
kubectl rollout status is the most convenient variant; it
waits for new and old ReplicaSets.
Save your progress? Sign up for free
Exercise: Speed Drills
- Which image does the Deployment
webuse? Only the image, nothing else. Target time: 30 s - How many CPUs and how much memory does each node have? Target time: 45 s
- What is the user in the Secret
db-zugang, in plain text? Target time: 30 s
Solution
kubectl -n laden get deploy web -o jsonpath='{.spec.template.spec.containers[0].image}{"\n"}'
kubectl get nodes -o custom-columns=NAME:.metadata.name,CPU:.status.capacity.cpu,MEM:.status.capacity.memory
kubectl -n laden get secret db-zugang -o jsonpath='{.data.DB_USER}' | base64 -d; echoExpected:
nginx:1.30.7-alpine
NAME CPU MEM
werkzeuge-control-plane 4 8131756Ki
werkzeuge-worker 4 8131756Ki
werkzeuge-worker2 4 8131756Ki
laden
All three nodes report the full 4 CPUs and 8 GB of the VM: kind nodes are containers without limits of their own. On real hardware, each server would stand for itself here. And Secrets are only Base64, not encryption. Day 4 shows a plugin that takes the decoding off your hands.
Save your progress? Sign up for free
Challenge
A security audit asks: “Which images run in the cluster, and how often?” One line, sorted by frequency, all containers, all namespaces.
Hint: Two nested range in JSONPath,
followed by sort | uniq -c. Or jq with
group_by.
Solution
kubectl get pods -A -o jsonpath='{range .items[*]}{range .spec.containers[*]}{.image}{"\n"}{end}{end}' | sort | uniq -c | sort -rn | head -8Expected (shortened):
3 registry.k8s.io/kube-proxy:v1.37.0
3 quay.io/cilium/cilium:v1.20.5@sha256:aa72499f075ad729947ea91b026218aceba24f1a8e4534bf36b8368c7c561526
3 quay.io/cilium/cilium-envoy:v1.39.6-1794557904-dee711ff0e84b106edd0abcdd71961af1b870359@sha256:bdef13043ebaa7b9dcd8e3a86be41080bb5369e017cd759a12daf89e2b8fafe7
3 nginx:1.30.7-alpine
2 traefik/whoami:v1.11.0
2 registry.k8s.io/coredns/coredns:v1.14.6
2 busybox:1.37.0
1 registry.k8s.io/kube-scheduler:v1.37.0
The same answer with jq:
kubectl get pods -A -o json | jq -r '[.items[].spec.containers[].image] | group_by(.) | map("\(length) \(.[0])") | .[]' | sort -rn | head -3Expected:
3 registry.k8s.io/kube-proxy:v1.37.0
3 quay.io/cilium/cilium:v1.20.5@sha256:aa72499f075ad729947ea91b026218aceba24f1a8e4534bf36b8368c7c561526
3 quay.io/cilium/cilium-envoy:v1.39.6-1794557904-dee711ff0e84b106edd0abcdd71961af1b870359@sha256:bdef13043ebaa7b9dcd8e3a86be41080bb5369e017cd759a12daf89e2b8fafe7
Notice: Cilium is pinned by digest (@sha256:…), the shop
only by tag. A tag can change, a digest cannot. Init containers are
missing in both variants; if you want to count them too, add
.spec.initContainers[].
Save your progress? Sign up for free
Checkpoint
kubectl get pods -A --field-selector=status.phase!=Running,status.phase!=Succeeded
kubectl -n laden get deploy web -o jsonpath='{.status.readyReplicas}{"\n"}'Expected:
No resources found
3
Interview Note
- JSONPath or jq? JSONPath for single values and simple filters, without an additional tool. jq as soon as it is about “any element”, grouping, counting or reshaping.
- Why can
kubectl wait --for=condition=Availablereturn too early?Availablemeans minimum availability, not “all replicas new and ready”. For rollouts userollout status, for exact states--for=jsonpath. - What can field selectors do? Filter on the server side, but only on a few fields defined per resource.
Enterprise Note
- Frequent queries do not belong in your memory but in a shared collection: shell aliases in the team repo or kubectl plugins (Day 4 and Day 14). Then everyone queries the same fact in the same way.
-o json | jqacross all namespaces loads many megabytes in large clusters. In automation, better narrow it down with a label or field selector; kubectl uses--chunk-sizeautomatically.