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 explainto find how to write a field such asreadinessProbe - Explain why
kubectl get alldoes 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:
kubectl config use-context kind-demo && kubectl create namespace explorerSwitched to context "kind-demo".namespace/explorer createdThe two lines confirm that kubectl is talking to the demo cluster and that
the namespace exists. Then create the working directory:
mkdir -p ~/atelier-k8s/explorer && cd ~/atelier-k8s/explorerWhy 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:
kubectl api-resources | grep -i deploymentdeployments deploy apps/v1 true DeploymentThe 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.
| Column | What it gives | Where you use it |
|---|---|---|
| NAME | The plural name of the resource | kubectl get <NAME> |
| SHORTNAMES | The abbreviation usable on the command line | kubectl get deploy instead of deployments |
| APIVERSION | The group and version of the API | The apiVersion: field of a manifest |
| NAMESPACED | true if the resource lives in a namespace, false if it is global to the cluster | Knowing whether -n applies |
| KIND | The exact type | The 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/v1kind: Deploymentmetadata: name: webspec: # the spec fields are looked up with kubectl explainFilter 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:
kubectl api-resources --api-group=appsNAME SHORTNAMES APIVERSION NAMESPACED KINDcontrollerrevisions apps/v1 true ControllerRevisiondaemonsets ds apps/v1 true DaemonSetdeployments deploy apps/v1 true Deploymentreplicasets rs apps/v1 true ReplicaSetstatefulsets sts apps/v1 true StatefulSetThis 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.
| Group | What it contains |
|---|---|
| (empty, core) | Pods, Services, ConfigMaps, Secrets, Namespaces, Nodes, PersistentVolumeClaims |
apps | Deployments, StatefulSets, DaemonSets, ReplicaSets |
batch | Jobs, CronJobs |
networking.k8s.io | Ingress, IngressClass, NetworkPolicy |
rbac.authorization.k8s.io | Roles, ClusterRoles, RoleBindings |
storage.k8s.io | StorageClasses, CSIDrivers, VolumeAttachments |
autoscaling | HorizontalPodAutoscaler |
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.
kubectl explain <type>kubectl explain <type>.<field>.<subfield>kubectl explain <type> --recursivekubectl 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:
kubectl explain deployment.spec.template.spec.containers --recursive | grep -A9 readinessProbe 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:
kubectl explain deployment.spec.template.spec.containers.readinessProbe.httpGetGROUP: appsKIND: DeploymentVERSION: 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.
kubectl explain pod.spec --recursive | lesskubectl explain deployment --recursive | grep -i tolerationThe 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:
cat > web.yaml <<'EOF'apiVersion: apps/v1kind: Deploymentmetadata: name: web labels: app: webspec: replicas: 2 selector: matchLabels: app: web template: metadata: labels: app: web spec: containers: - name: nginx image: nginx:1.30.5@sha256:9bf97bd7714f5e24c1ccd545ecb9eb5435cb6d109c97cebb15e7e455e0239edb ports: - containerPort: 80EOFkubectl apply -f web.yaml -n explorer && kubectl rollout status deployment/web -n explorer --timeout=90sdeployment.apps/web createdWaiting 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 outThe 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:
cp web.yaml web-sonde.yamlcat >> web-sonde.yaml <<'EOF' readinessProbe: httpGet: path: / port: 80EOFThe 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:
kubectl apply -f web-sonde.yaml -n explorer && kubectl rollout status deployment/web -n explorer --timeout=90sdeployment.apps/web configuredWaiting 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 outThe API accepted the probe, then Kubernetes replaced the Pods one by one. Check the Pods:
kubectl get pods -n explorer -l app=webNAME READY STATUS RESTARTS AGEweb-5f784567c7-rn294 1/1 Terminating 0 20sweb-6d8dfc5876-5frp2 1/1 Running 0 12sweb-6d8dfc5876-vznlm 1/1 Running 0 1sLook 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.
cat > crd-recette.yaml <<'EOF'apiVersion: apiextensions.k8s.io/v1kind: CustomResourceDefinitionmetadata: name: recettes.atelier.formation.k8sspec: 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.EOFkubectl apply -f crd-recette.yaml && kubectl wait --for=condition=Established crd/recettes.atelier.formation.k8s --timeout=60scustomresourcedefinition.apiextensions.k8s.io/recettes.atelier.formation.k8s createdcustomresourcedefinition.apiextensions.k8s.io/recettes.atelier.formation.k8s condition metThe Established condition means the API serves the new type. Look it up like
any type, by its group:
kubectl api-resources --api-group=atelier.formation.k8sNAME SHORTNAMES APIVERSION NAMESPACED KINDrecettes rct atelier.formation.k8s/v1 true RecetteThe Recette type appears in the list with its short name rct, on the same
footing as native types. Now ask explain for its fields:
kubectl explain recette.specGROUP: atelier.formation.k8sKIND: RecetteVERSION: 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:
cat > recette-sans-titre.yaml <<'EOF'apiVersion: atelier.formation.k8s/v1kind: Recettemetadata: name: galettespec: portions: 4EOFkubectl apply -f recette-sans-titre.yaml -n explorerThe Recette "galette" is invalid: spec.titre: Required valueThe message names the missing field, spec.titre, exactly the field that
explain flagged -required-. Add it and the object is created:
cat > galette.yaml <<'EOF'apiVersion: atelier.formation.k8s/v1kind: Recettemetadata: name: galettespec: titre: Galette de sarrasin portions: 4EOFkubectl apply -f galette.yaml -n explorer && kubectl get recette -n explorerrecette.atelier.formation.k8s/galette createdNAME AGEgalette 0sThe 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:
kubectl create configmap reglages -n explorer --from-literal=MODE=demokubectl create secret generic acces -n explorer --from-literal=jeton=valeur-de-demokubectl create serviceaccount lecteur -n explorerconfigmap/reglages createdsecret/acces createdserviceaccount/lecteur createdNow list the namespace with get all:
kubectl get all -n explorerNAME READY STATUS RESTARTS AGEpod/web-6d8dfc5876-5frp2 1/1 Running 0 15spod/web-6d8dfc5876-vznlm 1/1 Running 0 4s
NAME READY UP-TO-DATE AVAILABLE AGEdeployment.apps/web 2/2 2 2 23s
NAME DESIRED CURRENT READY AGEreplicaset.apps/web-5f784567c7 0 0 0 23sreplicaset.apps/web-6d8dfc5876 2 2 2 15sLook 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:
kubectl api-resources --categories=allNAME SHORTNAMES APIVERSION NAMESPACED KINDpods po v1 true Podreplicationcontrollers rc v1 true ReplicationControllerservices svc v1 true Servicedaemonsets ds apps/v1 true DaemonSetdeployments deploy apps/v1 true Deploymentreplicasets rs apps/v1 true ReplicaSetstatefulsets sts apps/v1 true StatefulSethorizontalpodautoscalers hpa autoscaling/v2 true HorizontalPodAutoscalercronjobs cj batch/v1 true CronJobjobs batch/v1 true JobConfigMaps, 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:
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--- configmaps ---kube-root-ca.crt 1 23sreglages 1 0s--- events ------ pods ---web-6d8dfc5876-5frp2 1/1 Running 0 15sweb-6d8dfc5876-vznlm 1/1 Running 0 4s--- secrets ---acces Opaque 1 0s--- serviceaccounts ---default 23slecteur 0s--- deployments.apps ---web 2/2 2 2 23s--- replicasets.apps ---web-5f784567c7 0 0 0 23sweb-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:
kubectl delete namespace explorer && kubectl delete crd recettes.atelier.formation.k8snamespace "explorer" deletedcustomresourcedefinition.apiextensions.k8s.io "recettes.atelier.formation.k8s" deletedCheck that the cluster is back to its initial state:
kubectl get crd && kubectl get namespace explorerNo resources foundError from server (NotFound): namespaces "explorer" not foundThe 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:
rm -rf ~/atelier-k8s/explorerTroubleshooting
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.
| Symptom | Likely cause | Solution |
|---|---|---|
explain answers the server doesn't have a resource type "deploymnet" | Resource name misspelled | Check with kubectl api-resources | grep -i <name> |
explain answers couldn't find resource for right after a CRD is created | The schema is not published yet | Run the command again one or two seconds later |
explain describes a different version than your manifest | The type is served in several versions | Add --api-version=<group/version> |
api-resources does not show an expected type | CRD not installed, or wrong cluster | Check kubectl get crd and your context |
kubectl get all does not show my Secrets or my Ingresses | get all only covers the all category | Use 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-resourceslists 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
-napplies. kubectl explainreads 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. --recursivedisplays the complete tree: combine it withgrepto find a field.- A CRD appears in
api-resourcesandexplainlike a native type; runexplainagain if the schema is not published yet. kubectl get allonly covers theallcategory: iterate overapi-resources --namespaced=true --verbs=listfor 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
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
Review
(0/0)Score by domain
A domain groups several guides and gets several questions, so its score is more reliable than a per-topic score, which often rests on a single question.
Summary
Strengths
No topic passed at 80% on at least two questions yet.
Weak areas
No topic below the pass mark.
Recommended next
Hints before you try again?
Continue the course: Write Kubernetes manifests: generate, validate, fix
A new full quiz with random questions
Work again only on the questions you missed