Lesson 24 · Section 2: Core Concepts
Lesson 24: kubectl explain: the API reference inside your terminal
How kubectl explain turns the cluster's own OpenAPI schema into field documentation, how to read its output, and how to use it to write correct manifests fast in the exam. · 15 min read · 4 min video
Official competencies this lesson covers
Narrated by the local narrator voice. Keys: Space plays and pauses, J and L step, C captions, F full screen.
Why it exists
A Kubernetes manifest is strict. Every field has one exact name, one exact place in the tree and one type, and the
API server rejects a file that gets any of them wrong. A Pod alone has several hundred fields once you count
everything nested under spec. Nobody keeps all of that in their head, and in the exam the clock punishes every
minute spent searching the website for whether it is nodeSelector or nodeselector, or whether tolerations
sits under the Pod or under the container.
kubectl explain answers those questions without leaving the terminal. You give it a resource type and,
optionally, a path to a field. It prints what that field is for, what type it takes and which fields are nested
under it.
It is easy to confuse with two neighbours, so fix the difference now:
| Command | Answers | Looks at |
|---|---|---|
kubectl explain pod.spec | What may I write here? | The type's schema |
kubectl describe pod web | What is happening to this object? | One live object and its events |
kubectl get pod web -o yaml | What is written in this object? | One live object |
What it is
The whole command is one argument and a few flags:
kubectl explain TYPE[.field[.field]...] [--recursive] [--api-version=group/version]
TYPE is anything kubectl get accepts as a resource name: the plural (pods), the singular (pod) or a short
name (po). After it comes the field path: field names joined by dots.
Parts:
- pod (resource type)
- spec (<PodSpec>)
- containers (<[]Container>)
- livenessProbe (<Probe>)
- httpGet (<HTTPGetAction>)
- port (<IntOrString> required)
Connections:
- pod to spec: .
- spec to containers: .
- containers to livenessProbe: .
- livenessProbe to httpGet: .
- httpGet to port: .
The path follows the YAML you would write. Where the manifest indents one level, the path gets one more dot:
spec: # pod.spec
containers: # pod.spec.containers
- name: web
livenessProbe: # pod.spec.containers.livenessProbe
httpGet: # pod.spec.containers.livenessProbe.httpGet
port: 8080 # pod.spec.containers.livenessProbe.httpGet.port
Two rules catch most people once:
- Lists have no index.
containersis a list, but you writepod.spec.containers.image, nevercontainers[0].image. The path describes the type of every item, not one item of one object. - Names are exact. Field names are camelCase and case sensitive.
pod.spec.nodeselectorfails withfield "nodeselector" does not exist;pod.spec.nodeSelectorworks.
Reading the output
$ kubectl explain pod.spec.tolerations
KIND: Pod
VERSION: v1
FIELD: tolerations <[]Toleration>
DESCRIPTION:
If specified, the pod's tolerations.
The pod this Toleration is attached to tolerates any taint that matches the
triple <key,value,effect> using the matching operator <operator>.
FIELDS:
effect <string>
enum: NoExecute, NoSchedule, PreferNoSchedule
Effect indicates the taint effect to match. Empty means match all taint
effects. ...
key <string>
Key is the taint key that the toleration applies to. ...
operator <string>
enum: Equal, Exists
Operator represents a key's relationship to the value. ...
tolerationSeconds <integer>
...
value <string>
...
(Descriptions are shortened here, and the exact layout differs a little between kubectl versions.)
| Part | What it tells you |
|---|---|
GROUP, KIND, VERSION | What goes at the top of the manifest. GROUP: apps and VERSION: v1 mean apiVersion: apps/v1. Core types such as Pod show no group, so it is just apiVersion: v1. |
FIELD | The field you asked about and its type |
DESCRIPTION | What the field does, often with its default and its limits |
FIELDS | Everything you may write one level below, each with its type |
-required- | The server rejects the object if this field is missing |
enum: | The only values the field accepts, spelled exactly |
The type in angle brackets tells you what shape of YAML to write:
| Type | Write | Example |
|---|---|---|
<string>, <integer>, <boolean> | A plain value | replicas: 3 |
<[]string> | A list of values | command: ["sleep", "3600"] |
<[]Container> | A list of objects: each item starts with - | containers: then - name: web |
<map[string]string> | Free key and value pairs | labels: then app: web |
<PodSpec>, <Probe>, <Object> | A nested object: explain it to see its fields | spec: |
<IntOrString> | A number or a string | maxSurge: 1 or maxSurge: 25% |
<Quantity> | A number with a unit | memory: 128Mi, cpu: 500m |
How it works
Parts:
- You (explain pod.spec)
- kubectl (walks the field path)
- API server (this cluster's version)
- Discovery (/api and /apis)
- OpenAPI v3 (/openapi/v3/...)
- CRD schemas (added on install)
- Field docs (names, types, text)
Connections:
- You to kubectl
- kubectl to API server: GET
- API server to Discovery: which type?
- API server to OpenAPI v3: its schema
- CRD schemas to OpenAPI v3: merged in
- kubectl to Field docs: prints
kubectl has no field documentation built in. Every time you run kubectl explain, it does three things:
- Finds the type. It uses the API server's discovery information (the same data behind
kubectl api-resources) to turnpo,podorpodsinto a precise group, version and kind. Discovery results are cached under~/.kube/cache, so this is usually instant. - Fetches the schema. The API server publishes an OpenAPI v3 document for every group and version, for example
/openapi/v3/api/v1for core types and/openapi/v3/apis/apps/v1for Deployments. kubectl downloads the one it needs. This is the same schema the server uses when it validates the manifests you apply. - Walks the path. Starting at the kind, it follows your field names one by one through the schema and prints the description, type and children of the place where it ends up.
Three consequences follow from that design, and each one matters in practice:
- The answer always matches the cluster. The website documents the newest release.
kubectl explaindocuments the API server you are talking to, so a field that was added or removed between versions shows up (or does not) exactly as that cluster will accept it. In an exam with several clusters, it answers for the current context. - Custom resources work. When a CustomResourceDefinition is installed, the API server adds its schema to the
same OpenAPI documents.
kubectl explainthen works on the new type like on any built-in one. How good the text is depends on the author: descriptions exist only if the CRD's schema contains them. - It needs a reachable cluster. With no connection there is nothing to read from, and the command fails. It does not need special rights, though: every authenticated user may read discovery and the OpenAPI documents.
Under the hood · What explain cannot tell you
-required-is not the whole truth. It marks fields the schema requires. Some rules are enforced in code after the schema check and are not marked. The classic case: a container'simageis not marked required, yet a Pod without one is rejected. When a field is obviously essential, set it even without the marker.- Rules between fields. That a toleration with
operator: Existsmust not setvalue, or that a field cannot be changed after creation, is written in the description at best. Read the description when a field behaves oddly. - Defaults are prose. There is no separate "default" line. Look for "Defaults to ..." in the description.
- Open-ended fields stop early. Some custom resources keep part of their schema open (any content allowed). There
explain shows
<Object>with no fields beneath it, and only the project's own documentation helps. - OpenAPI v2. Older kubectl versions read the single, large
/openapi/v2document instead, and--output=plaintext-openapiv2still asks for that rendering. The content is the same; only the layout differs.
Flags and variants
| You want | Command |
|---|---|
| The top level of a type | kubectl explain deployment |
| One field and its children, with descriptions | kubectl explain deployment.spec.strategy |
| The whole tree below a point, names and types only | kubectl explain deployment.spec.strategy --recursive |
| The tree, but only a few levels deep (recent kubectl) | kubectl explain pod --recursive --max-depth=2 |
| Another API version of the same kind | kubectl explain hpa.spec --api-version=autoscaling/v1 |
| The names and short names you can explain | kubectl api-resources |
--recursive trades descriptions for overview. Its output is an indented tree, where indentation means nesting:
$ kubectl explain deployment.spec.strategy --recursive
GROUP: apps
KIND: Deployment
VERSION: v1
FIELD: strategy <DeploymentStrategy>
DESCRIPTION:
The deployment strategy to use to replace existing pods with new ones.
FIELDS:
rollingUpdate <RollingUpdateDeployment>
maxSurge <IntOrString>
maxUnavailable <IntOrString>
type <string>
enum: Recreate, RollingUpdate
Without --api-version, explain shows the version the API server prefers for that kind. When a kind exists in
several versions with different fields, check the VERSION line before you copy field names into a manifest that
uses another apiVersion.
Using it
Parts:
- Exam task (add a toleration)
- --dry-run=client (writes the skeleton)
- kubectl explain (field names and types)
- kubernetes.io (complete examples)
- pod.yaml (edited by you)
- Cluster (kubectl apply -f)
Connections:
- Exam task to --dry-run=client
- Exam task to kubectl explain
- Exam task to kubernetes.io
- --dry-run=client to pod.yaml
- kubectl explain to pod.yaml
- kubernetes.io to pod.yaml
- pod.yaml to Cluster
kubectl explain does not write YAML for you. Its place is in the middle of the exam workflow: a dry run writes the
skeleton, explain supplies the fields the generator has no flag for, and you apply the result.
Example · Add a toleration to a Pod you generated
The task: run a Pod batch with image busybox:1.37 that may be scheduled on nodes tainted
dedicated=batch:NoSchedule. kubectl run has no flag for tolerations.
kubectl run batch --image=busybox:1.37 --dry-run=client -o yaml -- sleep 3600 > batch.yaml
kubectl explain pod.spec.tolerations
The first line of FIELD says <[]Toleration>, so it is a list, and it sits directly under spec, next to
containers. The FIELDS section gives the names, and the enum: lines the spelling of the values. Add to
batch.yaml:
spec:
tolerations:
- key: dedicated
operator: Equal
value: batch
effect: NoSchedule
kubectl apply -f batch.yaml
Example · Find a field when you only remember part of its name
You must make a Deployment's Pods wait 30 seconds before they are killed, and you remember only that the field has "grace" in its name. Search the tree, then read the one field:
kubectl explain deployment.spec.template.spec --recursive | grep -i grace
# terminationGracePeriodSeconds <integer>
# terminationGracePeriodSeconds <integer> (several more, deeper in)
kubectl explain deployment.spec.template.spec.terminationGracePeriodSeconds
There are several matches, and the indentation tells them apart. The one indented by only two spaces sits directly under the Pod spec: that is the one you want. The deeper ones belong to the containers' probes. The description confirms the unit (seconds) and the default (30).
Example · Write a custom resource you have never seen
An operator installed a CRD and the task asks for one of its objects. Find the type, then explore it like a built-in one. Here with the Gateway API's HTTPRoute:
kubectl api-resources --api-group=gateway.networking.k8s.io # names and short names
kubectl explain httproute # GROUP and VERSION for apiVersion
kubectl explain httproute.spec --recursive | less # the shape of the spec
kubectl explain httproute.spec.rules.backendRefs # the details you need
The header shows GROUP: gateway.networking.k8s.io and VERSION: v1, so the manifest starts with
apiVersion: gateway.networking.k8s.io/v1 and kind: HTTPRoute.
Example · Build a JSONPath query from the status fields
status is documented too, which helps when a task asks for a value from a live object. To print how often each
container of Pod web restarted:
kubectl explain pod.status.containerStatuses # shows restartCount <integer>
kubectl get pod web -o jsonpath='{.status.containerStatuses[*].restartCount}'
The JSONPath is the explain path with a leading dot, plus [*] (or an index) wherever explain showed a list type.
Tricks
Common mistakes
- An index in the path.
pod.spec.containers[0].imageis not a field path. Leave the index out. - Wrong case or number.
pod.spec.container,pod.spec.nodeselectoranddeployment.spec.Replicasall fail withfield ... does not exist. Run explain one level up and copy the name from theFIELDSlist. - Asking the wrong tool. explain never shows the values of an object in the cluster. For that, use
kubectl get -o yamlorkubectl describe. - Reading the wrong version. The fields under
hpa.specdiffer betweenautoscaling/v1andautoscaling/v2. Make sure theVERSIONline matches theapiVersionin your file, or pass--api-version. - Expecting descriptions from
--recursive. It prints names and types only. Use it to locate a field, then explain that field without the flag. - Trusting
-required-alone. A missing marker does not mean the object is valid without the field (see the deep dive above). A server-side dry run gives the final answer.
Recap
kubectl explainprints field documentation from the OpenAPI schema of the cluster you are connected to, CRDs included.- A path is the resource type, then field names joined by dots: exact camelCase, no list indexes.
- The output gives the
apiVersionparts, each field's type,-required-fields and allowedenumvalues. --recursiveshows the tree without descriptions;--api-versionpicks the version.- In the exam: generate the skeleton with a dry run, look up the missing fields with explain, apply.
Official docs
Quiz: check what you learned
5 questions on this lesson · about 3 min · instant feedback. Missed questions come back in your review queue.
Sign in to take the quiz and keep your score.
Practise: try it on a real cluster
2 hands-on labs for this lesson. You get goals, not steps: any solution that reaches them passes.
Answer three questions about the API with kubectl explain, then use a field you looked up.
Investigate · Level 1 · warm-up · target 10 min
Shape kubectl's output with jsonpath, custom columns, sorting and field selectors to answer four questions about a cluster without scrolling through YAML.
Investigate · Level 2 · standard · target 20 min
Discussion
Learners ask and answer questions here. Sign in to read and join the discussion.