Skip to content
LF Cert Trainer

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

1/10kubectl explain
0:00 / 3:53

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:

CommandAnswersLooks at
kubectl explain pod.specWhat may I write here?The type's schema
kubectl describe pod webWhat is happening to this object?One live object and its events
kubectl get pod web -o yamlWhat 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.

A field path is the route through the manifest.....podresource typespec<PodSpec>containers<[]Container>livenessProbe<Probe>httpGet<HTTPGetAction>port<IntOrString> required
A field path is the route through the manifest. Each dot goes one level deeper, exactly as the indentation does in YAML. The type in angle brackets tells you what to write at that level: a value, a list or a nested object.

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. containers is a list, but you write pod.spec.containers.image, never containers[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.nodeselector fails with field "nodeselector" does not exist; pod.spec.nodeSelector works.

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.)

PartWhat it tells you
GROUP, KIND, VERSIONWhat 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.
FIELDThe field you asked about and its type
DESCRIPTIONWhat the field does, often with its default and its limits
FIELDSEverything 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:

TypeWriteExample
<string>, <integer>, <boolean>A plain valuereplicas: 3
<[]string>A list of valuescommand: ["sleep", "3600"]
<[]Container>A list of objects: each item starts with -containers: then - name: web
<map[string]string>Free key and value pairslabels: then app: web
<PodSpec>, <Probe>, <Object>A nested object: explain it to see its fieldsspec:
<IntOrString>A number or a stringmaxSurge: 1 or maxSurge: 25%
<Quantity>A number with a unitmemory: 128Mi, cpu: 500m

How it works

Where the text of kubectl explain comes fromGETwhich type?its schemamerged inprintsYouexplain pod.speckubectlwalks the field pathAPI serverthis cluster's versionDiscovery/api and /apisOpenAPI v3/openapi/v3/...CRD schemasadded on installField docsnames, types, text
Where the text of kubectl explain comes from. Nothing is built into kubectl. It asks the API server which type you mean, downloads that API version's OpenAPI schema, and prints the part your field path points at. Custom resources are in the same schema.

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:

  1. Finds the type. It uses the API server's discovery information (the same data behind kubectl api-resources) to turn po, pod or pods into a precise group, version and kind. Discovery results are cached under ~/.kube/cache, so this is usually instant.
  2. Fetches the schema. The API server publishes an OpenAPI v3 document for every group and version, for example /openapi/v3/api/v1 for core types and /openapi/v3/apis/apps/v1 for Deployments. kubectl downloads the one it needs. This is the same schema the server uses when it validates the manifests you apply.
  3. 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 explain documents 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 explain then 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's image is 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: Exists must not set value, 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/v2 document instead, and --output=plaintext-openapiv2 still asks for that rendering. The content is the same; only the layout differs.

Flags and variants

You wantCommand
The top level of a typekubectl explain deployment
One field and its children, with descriptionskubectl explain deployment.spec.strategy
The whole tree below a point, names and types onlykubectl 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 kindkubectl explain hpa.spec --api-version=autoscaling/v1
The names and short names you can explainkubectl 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

Three helpers, three jobsExam taskadd a toleration--dry-run=clientwrites the skeletonkubectl explainfield names and typeskubernetes.iocomplete examplespod.yamledited by youClusterkubectl apply -f
Three helpers, three jobs. Let a dry run write the skeleton, let explain tell you the exact names and types of the fields you must add, and open the website only when you need a complete example.

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].image is not a field path. Leave the index out.
  • Wrong case or number. pod.spec.container, pod.spec.nodeselector and deployment.spec.Replicas all fail with field ... does not exist. Run explain one level up and copy the name from the FIELDS list.
  • Asking the wrong tool. explain never shows the values of an object in the cluster. For that, use kubectl get -o yaml or kubectl describe.
  • Reading the wrong version. The fields under hpa.spec differ between autoscaling/v1 and autoscaling/v2. Make sure the VERSION line matches the apiVersion in 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 explain prints 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 apiVersion parts, each field's type, -required- fields and allowed enum values.
  • --recursive shows the tree without descriptions; --api-version picks 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.