Skip to content
Français
Account: not signed in, sync available My learning
Select theme
Français

kubectl api-resources and explain: explore the Kubernetes API

By updated

Improve this page

Logo Kubernetes

You want to add a readiness probe to a Deployment and you do not have the documentation at hand. Two commands are enough, because they query your cluster rather than a website: kubectl api-resources gives the kind and the apiVersion of a resource type, and kubectl explain describes its fields. This lesson has you use them on a single thread: you look up the syntax of a probe, you add it to a Deployment, you find a type added by a CRD, then you see what kubectl get all does not show.

What you will learn

  • Find the name, the short name, the API group and the kind of a resource type, including one added by a CRD
  • Work out from the output the kind and the apiVersion to write in a manifest
  • Walk through the structure of an object with kubectl explain to find how to write a field such as readinessProbe
  • Explain why kubectl get all does not list everything, and take a full inventory of a namespace

Prerequisites

You have the demo cluster from First cluster and a kubectl that reaches it. You know how to create a Deployment with a manifest, as in the lesson Deployments, and you know what a namespace is.

Set up the workshop

The demonstration works in a namespace called explorer, which is deleted at the end, and in a working directory ~/atelier-k8s/explorer/. Create the namespace after selecting the context of the demo cluster:

Terminal window
kubectl config use-context kind-demo && kubectl create namespace explorer
Output
Switched to context "kind-demo".
namespace/explorer created

The two lines confirm that kubectl is talking to the demo cluster and that the namespace exists. Then create the working directory:

Terminal window
mkdir -p ~/atelier-k8s/explorer && cd ~/atelier-k8s/explorer

Why query the cluster rather than online documentation?

kubectl explain reads the OpenAPI schema published by the API server of your cluster, and kubectl api-resources reads its list of served types. Both therefore answer for your version of Kubernetes and for the types your operators added: a tutorial found online may describe an apiVersion that has since been removed, your cluster never will. Remember the split of roles: api-resources is the directory of types, explain is their dictionary.

kubectl api-resources: find the right resource type

To write a probe in a Deployment, you first need to know how the API spells Deployment. kubectl api-resources prints every type the cluster can serve. Its output is long, so you filter it:

Terminal window
kubectl api-resources | grep -i deployment
Output
deployments deploy apps/v1 true Deployment

The grep filter also drops the header line, hence the missing column names. Read the line from left to right: the type is called deployments, is shortened to deploy, lives in the apps group in version v1, exists inside a namespace (true) and has the kind Deployment.

What the output tells you

Each column answers a precise question, and two of them are copied as is into a manifest: APIVERSION and KIND. The NAMESPACED column tells you whether the -n option makes sense for this type.

ColumnWhat it givesWhere you use it
NAMEThe plural name of the resourcekubectl get <NAME>
SHORTNAMESThe abbreviation usable on the command linekubectl get deploy instead of deployments
APIVERSIONThe group and version of the APIThe apiVersion: field of a manifest
NAMESPACEDtrue if the resource lives in a namespace, false if it is global to the clusterKnowing whether -n applies
KINDThe exact typeThe kind: field of a manifest

How do you find the kind and apiVersion for a manifest?

The gesture takes three steps, and it works for any type, CRDs included: look the type up by name with grep, read the APIVERSION and KIND columns, copy the two values at the top of the manifest. For the Deployment of the previous output, this gives the following, and kubectl explain is then used to fill in spec:

apiVersion: apps/v1
kind: Deployment
metadata:
name: web
spec:
# the spec fields are looked up with kubectl explain

Filter the resources

When you do not know the exact name, filter rather than read the whole list. The --api-group option isolates a functional family in one go:

Terminal window
kubectl api-resources --api-group=apps
Output
NAME SHORTNAMES APIVERSION NAMESPACED KIND
controllerrevisions apps/v1 true ControllerRevision
daemonsets ds apps/v1 true DaemonSet
deployments deploy apps/v1 true Deployment
replicasets rs apps/v1 true ReplicaSet
statefulsets sts apps/v1 true StatefulSet

This time the header is visible and the five types of the apps group come out together. Two other filters combine with this one: --namespaced=false keeps only the resources that are global to the cluster, and --categories=all lists the types that kubectl get all covers, which is useful further down.

Which API groups are common?

The API group is the part of the apiVersion before the slash: apps in apps/v1. The core group, the one of the historical resources, has no name, hence an apiVersion reduced to v1 for a Pod or a Service. The seven groups in the table are enough to guess the apiVersion of most objects in this course.

GroupWhat it contains
(empty, core)Pods, Services, ConfigMaps, Secrets, Namespaces, Nodes, PersistentVolumeClaims
appsDeployments, StatefulSets, DaemonSets, ReplicaSets
batchJobs, CronJobs
networking.k8s.ioIngress, IngressClass, NetworkPolicy
rbac.authorization.k8s.ioRoles, ClusterRoles, RoleBindings
storage.k8s.ioStorageClasses, CSIDrivers, VolumeAttachments
autoscalingHorizontalPodAutoscaler

kubectl explain: explore the structure of an object

kubectl explain displays the documentation of a type or a field: its description, its type (<string>, <integer>, <[]Container> for a list) and its subfields. You stay in the terminal while you write the manifest.

Syntax

The dotted notation follows the hierarchy of your YAML. The path deployment.spec.template.spec.containers reproduces the indentation levels you will write, which lets you go down field by field without displaying the whole object. The --recursive option does the opposite: the whole tree at once, best kept for a grep.

Terminal window
kubectl explain <type>
kubectl explain <type>.<field>.<subfield>
kubectl explain <type> --recursive
kubectl explain <type> --api-version=<group/version>

The first form gives the overview of a type, the second a specific field, the third the complete tree, and the last forces an API version when a type is served in several versions.

How do you find the syntax of a readinessProbe?

You know that a container accepts a readinessProbe (the lesson Probes teaches it in detail), but not how to write it. Go down from the broadest to the most precise. First look for the field in the containers tree, keeping the lines that follow its name:

Terminal window
kubectl explain deployment.spec.template.spec.containers --recursive | grep -A9 readinessProbe
Output
readinessProbe <Probe>
exec <ExecAction>
command <[]string>
failureThreshold <integer>
grpc <GRPCAction>
mode <string>
enum: Plaintext, TLS
port <integer> -required-
service <string>
httpGet <HTTPGetAction>

The subfields are sorted alphabetically, not by importance: httpGet, the most common probe mode, comes after exec and grpc. The -required- mention flags a field that is mandatory in its parent (here port in grpc). Now go down into httpGet:

Terminal window
kubectl explain deployment.spec.template.spec.containers.readinessProbe.httpGet
Output
GROUP: apps
KIND: Deployment
VERSION: v1
FIELD: httpGet <HTTPGetAction>
DESCRIPTION:
HTTPGet specifies an HTTP GET request to perform.
HTTPGetAction describes an action based on HTTP Get requests.
FIELDS:
host <string>
Host name to connect to, defaults to the pod IP. You probably want to set
"Host" in httpHeaders instead.
httpHeaders <[]HTTPHeader>
Custom headers to set in the request. HTTP allows repeated headers.
path <string>
Path to access on the HTTP server.
port <IntOrString> -required-
Name or number of the port to access on the container. Number must be in the
range 1 to 65535. Name must be an IANA_SVC_NAME.
protocol <string>
enum: HTTP1, HTTP2
Protocol selects the wire protocol for the probe connection. Nil defaults to
HTTP/1.1.
Possible enum values:
- `"HTTP1"` uses HTTP/1.1 (the existing default).
- `"HTTP2"` uses HTTP/2. Currently, only cleartext with prior knowledge
(h2c) is supported, and must be used with scheme HTTP.
scheme <string>
enum: HTTP, HTTPS
Scheme to use for connecting to the host. Defaults to HTTP.
Possible enum values:
- `"HTTP"` means that the scheme used will be http://
- `"HTTPS"` means that the scheme used will be https://

Look at three things. The GROUP, KIND, VERSION header confirms the API version being described. port carries -required-: it is the only field you cannot omit in an httpGet. An enum: line lists the only accepted values, for example HTTP or HTTPS for scheme. You now have what you need to write the probe.

Explore the full tree of an object

When you know the name of a field but not how deep it lives, --recursive displays all the fields of a type as an indented tree, without the descriptions. The output for a Deployment is very long: browse it with less or filter it with grep, as above.

Terminal window
kubectl explain pod.spec --recursive | less
kubectl explain deployment --recursive | grep -i toleration

The indentation of the line you find gives its depth; to read its neighbors as well, widen the context with grep -B2 -A5.

Add the probe to a Deployment

First create a web Deployment without a probe, with the reference image of the module, pinned by its digest:

Terminal window
cat > web.yaml <<'EOF'
apiVersion: apps/v1
kind: Deployment
metadata:
name: web
labels:
app: web
spec:
replicas: 2
selector:
matchLabels:
app: web
template:
metadata:
labels:
app: web
spec:
containers:
- name: nginx
image: nginx:1.30.5@sha256:9bf97bd7714f5e24c1ccd545ecb9eb5435cb6d109c97cebb15e7e455e0239edb
ports:
- containerPort: 80
EOF
kubectl apply -f web.yaml -n explorer && kubectl rollout status deployment/web -n explorer --timeout=90s
Output
deployment.apps/web created
Waiting for deployment "web" rollout to finish: 0 out of 2 new replicas have been updated...
Waiting for deployment "web" rollout to finish: 0 of 2 updated replicas are available...
Waiting for deployment "web" rollout to finish: 1 of 2 updated replicas are available...
deployment "web" successfully rolled out

The kubectl rollout status command waits for the rollout to finish: the last line says that both Pods are ready. Now copy the file under another name and add the block found with explain, at the same level as ports in the container:

Terminal window
cp web.yaml web-sonde.yaml
cat >> web-sonde.yaml <<'EOF'
readinessProbe:
httpGet:
path: /
port: 80
EOF

The block appended at the end of the file lands in the container, because ports is the last field of the original file. Apply the result:

Terminal window
kubectl apply -f web-sonde.yaml -n explorer && kubectl rollout status deployment/web -n explorer --timeout=90s
Output
deployment.apps/web configured
Waiting for deployment "web" rollout to finish: 1 out of 2 new replicas have been updated...
Waiting for deployment "web" rollout to finish: 1 out of 2 new replicas have been updated...
Waiting for deployment "web" rollout to finish: 1 out of 2 new replicas have been updated...
Waiting for deployment "web" rollout to finish: 1 old replicas are pending termination...
Waiting for deployment "web" rollout to finish: 1 old replicas are pending termination...
Waiting for deployment "web" rollout to finish: 1 old replicas are pending termination...
deployment "web" successfully rolled out

The API accepted the probe, then Kubernetes replaced the Pods one by one. Check the Pods:

Terminal window
kubectl get pods -n explorer -l app=web
Output
NAME READY STATUS RESTARTS AGE
web-5f784567c7-rn294 1/1 Terminating 0 20s
web-6d8dfc5876-5frp2 1/1 Running 0 12s
web-6d8dfc5876-vznlm 1/1 Running 0 1s

Look at the two names that share the prefix web-6d8dfc5876: they are the Pods of the new ReplicaSet, created after the template was modified. The Pod web-5f784567c7-rn294 belongs to the old one and is finishing its shutdown, hence its Terminating status; run the command again after a few seconds and it is gone. The READY column at 1/1 shows that the probe succeeds on the new Pods.

Find a type added by a CRD

A CRD (CustomResourceDefinition) adds a new type to the API. This is how an operator such as cert-manager brings its Certificate type. The added type then appears in api-resources and explain like a native type. This lesson does not teach you to write a CRD: the file is provided, and it defines an invented type Recette in the group atelier.formation.k8s, with a required field titre. The names are French on purpose, Recette being a recipe and titre its title, so that the outputs stay those of the tested cluster. The mechanism of operators is taught in the lesson Kubernetes Operators.

Terminal window
cat > crd-recette.yaml <<'EOF'
apiVersion: apiextensions.k8s.io/v1
kind: CustomResourceDefinition
metadata:
name: recettes.atelier.formation.k8s
spec:
group: atelier.formation.k8s
scope: Namespaced
names:
plural: recettes
singular: recette
kind: Recette
shortNames:
- rct
versions:
- name: v1
served: true
storage: true
schema:
openAPIV3Schema:
type: object
properties:
spec:
type: object
required:
- titre
properties:
titre:
type: string
description: Nom de la recette, obligatoire.
portions:
type: integer
description: Nombre de portions.
EOF
kubectl apply -f crd-recette.yaml && kubectl wait --for=condition=Established crd/recettes.atelier.formation.k8s --timeout=60s
Output
customresourcedefinition.apiextensions.k8s.io/recettes.atelier.formation.k8s created
customresourcedefinition.apiextensions.k8s.io/recettes.atelier.formation.k8s condition met

The Established condition means the API serves the new type. Look it up like any type, by its group:

Terminal window
kubectl api-resources --api-group=atelier.formation.k8s
Output
NAME SHORTNAMES APIVERSION NAMESPACED KIND
recettes rct atelier.formation.k8s/v1 true Recette

The Recette type appears in the list with its short name rct, on the same footing as native types. Now ask explain for its fields:

Terminal window
kubectl explain recette.spec
Output
GROUP: atelier.formation.k8s
KIND: Recette
VERSION: v1
FIELD: spec <Object>
DESCRIPTION:
<empty>
FIELDS:
portions <integer>
Nombre de portions.
titre <string> -required-
Nom de la recette, obligatoire.

The titre field carries -required- and the descriptions come from the schema of the CRD: explain reads an added type exactly like a native one. If explain answers couldn't find resource for "atelier.formation.k8s/v1, Resource=recettes" right after the CRD is created, run the command again one or two seconds later: the server publishes the schema a little after declaring the type established.

Make use of this schema. A file without the required field is rejected by the API:

Terminal window
cat > recette-sans-titre.yaml <<'EOF'
apiVersion: atelier.formation.k8s/v1
kind: Recette
metadata:
name: galette
spec:
portions: 4
EOF
kubectl apply -f recette-sans-titre.yaml -n explorer
Output
The Recette "galette" is invalid: spec.titre: Required value

The message names the missing field, spec.titre, exactly the field that explain flagged -required-. Add it and the object is created:

Terminal window
cat > galette.yaml <<'EOF'
apiVersion: atelier.formation.k8s/v1
kind: Recette
metadata:
name: galette
spec:
titre: Galette de sarrasin
portions: 4
EOF
kubectl apply -f galette.yaml -n explorer && kubectl get recette -n explorer
Output
recette.atelier.formation.k8s/galette created
NAME AGE
galette 0s

The kubectl get all trap

The kubectl get all command is often the first one you learn, and it does not show everything: it only displays the types that carry the all category. Add a ConfigMap, a Secret and a ServiceAccount to the namespace, three objects an inventory must find:

Terminal window
kubectl create configmap reglages -n explorer --from-literal=MODE=demo
kubectl create secret generic acces -n explorer --from-literal=jeton=valeur-de-demo
kubectl create serviceaccount lecteur -n explorer
Output
configmap/reglages created
secret/acces created
serviceaccount/lecteur created

Now list the namespace with get all:

Terminal window
kubectl get all -n explorer
Output
NAME READY STATUS RESTARTS AGE
pod/web-6d8dfc5876-5frp2 1/1 Running 0 15s
pod/web-6d8dfc5876-vznlm 1/1 Running 0 4s
NAME READY UP-TO-DATE AVAILABLE AGE
deployment.apps/web 2/2 2 2 23s
NAME DESIRED CURRENT READY AGE
replicaset.apps/web-5f784567c7 0 0 0 23s
replicaset.apps/web-6d8dfc5876 2 2 2 15s

Look for what is missing: neither the reglages ConfigMap, nor the acces Secret, nor the lecteur ServiceAccount, nor the galette recipe, even though they do exist. You can also see the old ReplicaSet at zero replicas, kept for a possible rollback. To know what get all covers, ask for the list of the types in its category:

Terminal window
kubectl api-resources --categories=all
Output
NAME SHORTNAMES APIVERSION NAMESPACED KIND
pods po v1 true Pod
replicationcontrollers rc v1 true ReplicationController
services svc v1 true Service
daemonsets ds apps/v1 true DaemonSet
deployments deploy apps/v1 true Deployment
replicasets rs apps/v1 true ReplicaSet
statefulsets sts apps/v1 true StatefulSet
horizontalpodautoscalers hpa autoscaling/v2 true HorizontalPodAutoscaler
cronjobs cj batch/v1 true CronJob
jobs batch/v1 true Job

ConfigMaps, Secrets, ServiceAccounts, Ingresses, PersistentVolumeClaims, NetworkPolicies, Roles and the objects of CRDs are not there. An inventory built on get all therefore lets important resources slip under the radar.

List everything in a namespace

For a full inventory, ask api-resources for all the namespaced types that accept the list verb, then query them one by one. The loop only prints the types that have at least one object, preceded by their name:

Terminal window
kubectl api-resources --namespaced=true --verbs=list -o name \
| while read kind; do
output=$(kubectl get "$kind" -n explorer --no-headers 2>/dev/null)
if [ -n "$output" ]; then
echo "--- $kind ---"
echo "$output"
fi
done
Output (excerpt, event lines cut)
--- configmaps ---
kube-root-ca.crt 1 23s
reglages 1 0s
--- events ---
--- pods ---
web-6d8dfc5876-5frp2 1/1 Running 0 15s
web-6d8dfc5876-vznlm 1/1 Running 0 4s
--- secrets ---
acces Opaque 1 0s
--- serviceaccounts ---
default 23s
lecteur 0s
--- deployments.apps ---
web 2/2 2 2 23s
--- replicasets.apps ---
web-5f784567c7 0 0 0 23s
web-6d8dfc5876 2 2 2 15s
--- recettes.atelier.formation.k8s ---
galette 0s
--- events.events.k8s.io ---

This time, everything get all kept quiet about shows up: the reglages ConfigMap (next to kube-root-ca.crt, created in every namespace), the acces Secret, the default and lecteur ServiceAccounts, and the galette recipe. Events come out twice, under events then events.events.k8s.io, because this type is served by two API groups. There are many of them, hence the cut in the excerpt.

Clean up the cluster

Delete the namespace, which takes the Deployment, the ConfigMap, the Secret, the ServiceAccount and the recipe with it, then the CRD, which is global to the cluster and therefore does not follow the namespace:

Terminal window
kubectl delete namespace explorer && kubectl delete crd recettes.atelier.formation.k8s
Output
namespace "explorer" deleted
customresourcedefinition.apiextensions.k8s.io "recettes.atelier.formation.k8s" deleted

Check that the cluster is back to its initial state:

Terminal window
kubectl get crd && kubectl get namespace explorer
Output
No resources found
Error from server (NotFound): namespaces "explorer" not found

The first line says that no CRD remains on this fresh cluster, the second that the namespace is gone; the return code is 1 because of the NotFound, which is the expected result. Finally, delete the working directory:

Terminal window
rm -rf ~/atelier-k8s/explorer

Troubleshooting

Before going through the table, check the context with kubectl config current-context: querying the wrong cluster is the most common cause. A type missing from api-resources may come from a CRD that is not installed, and a get that is refused on a type that is nevertheless listed is a matter of your RBAC permissions.

SymptomLikely causeSolution
explain answers the server doesn't have a resource type "deploymnet"Resource name misspelledCheck with kubectl api-resources | grep -i <name>
explain answers couldn't find resource for right after a CRD is createdThe schema is not published yetRun the command again one or two seconds later
explain describes a different version than your manifestThe type is served in several versionsAdd --api-version=<group/version>
api-resources does not show an expected typeCRD not installed, or wrong clusterCheck kubectl get crd and your context
kubectl get all does not show my Secrets or my Ingressesget all only covers the all categoryUse the loop over api-resources or target the type

Put it into practice

The lab puts you in front of a CRD you have never seen. You find its apiVersion and its kind with kubectl api-resources. You then create an object of that type, with fields that only explain reveals to you. You add an HTTP readiness probe to a Deployment, looking up its fields one by one. You finish with the full inventory of a namespace, beyond kubectl get all. The validation covers the state of the cluster and your record: the object exists with its required fields, the Pods are ready, and every type of object in the namespace is named.

Key takeaways

  • kubectl api-resources lists the types your cluster can serve, CRDs included: it is the directory.
  • Its APIVERSION and KIND columns are copied as is into a manifest; NAMESPACED tells you whether -n applies.
  • kubectl explain reads the OpenAPI schema of the server: it describes the fields of your version of Kubernetes.
  • The dotted notation follows the indentation of the YAML; -required- flags a mandatory field.
  • --recursive displays the complete tree: combine it with grep to find a field.
  • A CRD appears in api-resources and explain like a native type; run explain again if the schema is not published yet.
  • kubectl get all only covers the all category: iterate over api-resources --namespaced=true --verbs=list for a full inventory.

Test your knowledge

Six questions to check that you can find a type, read its apiVersion, navigate its fields with explain and stop relying on kubectl get all for an inventory.

Knowledge check

Check what you have learned with this interactive quiz

6 questions
5 min
80% to pass

How it works

  • The timer starts when you click Start
  • Multiple choice, true/false and short answer questions
  • You can move between questions
  • Detailed results are shown at the end

Starts the quiz and the timer