Skip to content
Latchkey

kubectl get -o jsonpath: Extract Fields to Gate CI

kubectl get -o jsonpath=<expr> extracts a specific field (or list) from a resource so a pipeline can test or store it.

Parsing kubectl output with grep is fragile. jsonpath addresses the exact field you want and is stable across kubectl versions.

What it does

kubectl get with -o jsonpath evaluates a JSONPath expression against the resource JSON and prints the matched value(s). range/end iterate lists, {"\n"} injects newlines, and the result is plain text suited to assigning to a shell variable.

Common usage

Terminal
kubectl get deploy api -o jsonpath='{.status.readyReplicas}'
# all pod names matching a label, one per line
kubectl get pods -l app=api \
  -o jsonpath='{range .items[*]}{.metadata.name}{"\n"}{end}'
# gate: fail if no ready replicas
test "$(kubectl get deploy api -o jsonpath='{.status.readyReplicas}')" \
  -ge 1 || exit 1

Options

SyntaxWhat it does
-o jsonpath='{path}'Print the value at the JSONPath
{range .items[*]} ... {end}Iterate over a list
{.a.b}Navigate nested fields
{"\n"} / {"\t"}Insert a newline or tab between values
-o jsonpath-as-jsonEmit the matched value as JSON (1.24+)

In CI

Quote the whole expression in single quotes so the shell does not expand $ or {}. For a field that may be absent (like readyReplicas on a brand-new deploy), jsonpath prints an empty string, so guard the comparison or use kubectl wait instead of polling.

Common errors in CI

"error: error parsing jsonpath ... unrecognized character" usually means the shell ate part of the expression; wrap it in single quotes. "error: ... is not found" with -o jsonpath is rare since missing fields yield empty output, but a wrong root (querying .spec of a list without .items) returns nothing. Comparing an empty string with -ge throws "integer expression expected"; default it to 0.

Related guides

Run this faster and cheaper on Latchkey managed runners. Start free →