Kubernetes foundations: the cluster and kubectl · 6 MIN READ

Anatomy of an object: apiVersion, kind, metadata, spec and status

Write a manifest from scratch or from a dry-run scaffold, tell spec from status, choose between labels and annotations, look fields up with kubectl explain, read live state with jsonpath and recognise strict validation errors.

Everything in Kubernetes is an object stored by the API server, and every object has the same shape. Once you can read that shape you can write manifests without copying them blindly, find any field with kubectl explain, and query live state precisely instead of scanning tables. The API server is strict about the shape too: a misspelt field is an error, not something it quietly ignores.

kubernetes · A MAP OF THE IDEA

  1. Scaffold with --dry-run
  2. Look fields up with explain
  3. Apply and fix strict errors
  4. Read status with jsonpath

Useful when

  • One uniform shape for every kind makes any object readable.
  • Strict validation turns typos into errors at apply time.

Watch out

  • A valid field in the wrong place still passes validation.
  • Status is current only when observedGeneration equals generation.

Implementation & operation cost: Learning to navigate schemas with explain and to query state with jsonpath instead of reading tables.

01

Four fields you write and one you read

apiVersion and kind select the schema: apps/v1 Deployment, v1 Pod, batch/v1 Job, networking.k8s.io/v1 Ingress. The part before the slash is the API group, and the core group has none. metadata identifies the object: name (unique per kind and namespace), namespace, labels and annotations; the server adds uid, resourceVersion, generation and creationTimestamp. spec is the desired state and belongs to you. status is the observed state and belongs to the controller that manages the object. You never write status in a manifest, and an update through the main resource cannot change it, because status is a separate subresource that the controller writes. When spec and status disagree, the object is still converging or something is stuck, and status usually says which.

yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: web
  labels:
    app: web
  annotations:
    team.example.com/owner: payments
    team.example.com/runbook: https://wiki.example.com/web
spec:
  replicas: 2
  selector:
    matchLabels:
      app: web
  template:
    metadata:
      labels:
        app: web
    spec:
      containers:
      - name: nginx
        image: nginx:1.27
        ports:
        - containerPort: 80
Read the code

There are two metadata blocks: the Deployment's own and the pod template's. Only the template becomes pods, so labels on the Deployment itself never reach them, and the selector must match the template's labels or the API server rejects the object. No namespace is set, so the manifest lands wherever kubectl points, which keeps it reusable. The runbook link is an annotation because nothing will ever select on it.

02

Labels select, annotations describe

Labels are short key-value pairs that the system queries: selectors in ReplicaSets, Services and NetworkPolicies, and kubectl -l, all match on labels. Keys may carry a DNS prefix, as in app.kubernetes.io/name, and values are at most 63 characters of letters, digits, dashes, underscores and dots. Annotations hold everything that is not used for selection: owners, runbook links, build commits, and settings read by tools, which is why ingress controllers are configured through annotations. They can be large, up to 256 KiB per object in total, and they are not indexed. The rule of thumb: if you would ever write -l key=value or a selector with it, make it a label; otherwise make it an annotation. The recommended app.kubernetes.io labels (name, instance, version, component, part-of, managed-by) give tools a shared vocabulary.

03

Find fields with explain, scaffold with --dry-run

You do not need to memorise schemas. kubectl explain prints the documentation of any field path from the server's OpenAPI schema, so it matches your cluster's version exactly, and --recursive shows a whole subtree at once. For a starting manifest, let kubectl generate one: the imperative create commands accept --dry-run=client -o yaml, which builds the object locally and prints it instead of sending it. The output may contain empty placeholder fields you can delete, and it lacks things you will want, such as resource requests and probes. Edit the file and keep it; the scaffold is a typing aid, not the deliverable. --dry-run=server goes one step further: the API server runs defaulting, validation and admission on the object but stores nothing.

bash
kubectl explain deployment.spec
kubectl explain pod.spec.containers
kubectl create deployment web --image=nginx:1.27 --replicas=2 --dry-run=client -o yaml > web.yaml
Read the code

explain deployment.spec lists replicas, selector, template, strategy and the other fields with their types; explain pod.spec.containers does the same one level down, including image, ports, env, resources and the three probes. In the lab the descriptions are short notes; on a real cluster they are the full API documentation. The last command writes a complete Deployment to web.yaml and creates nothing.

04

Strict validation: typos are errors

kubectl asks the API server for strict field validation by default (--validate=strict). A field the schema does not know, or a field given twice, fails the whole request instead of being dropped. That turns a misspelt imagee, or a readinessProbe indented under the wrong parent, into an immediate error that names the exact path, rather than a Deployment that silently ignores half of what you wrote. Wrong types are rejected as well, such as replicas: "2" written as a string. Use --validate=warn only when you must apply manifests written for a newer API, and treat every warning as a bug. Validation cannot catch a valid field in a place where it is also valid, such as a label put on the Deployment's metadata instead of the template's, so read manifests critically.

05

Read live state: -o yaml, jsonpath and custom columns

kubectl get -o yaml shows the object as stored, including the defaults the server added, such as the RollingUpdate strategy, and the full status. For scripts and quick checks, -o jsonpath extracts exact fields and -o custom-columns builds a table of your own. Compare metadata.generation, which increases on every spec change, with status.observedGeneration: while they differ, the controller has not processed your latest change, and the rest of status describes an older spec. Conditions are the structured part of status, a list of entries with type, status and reason, such as Available and Progressing for a Deployment; kubectl wait and rollout status read them too. Prefer these fields to parsing table output, whose columns are meant for people and may change between versions.

bash
kubectl get deployment web -o jsonpath='{.metadata.generation} {.status.observedGeneration}{"\n"}'
kubectl get deployment web -o jsonpath='{.status.conditions[?(@.type=="Available")].status}{"\n"}'
kubectl get pods -o custom-columns=NAME:.metadata.name,PHASE:.status.phase,NODE:.spec.nodeName
Read the code

The jsonpath expressions print bare values, such as 2 2 for generation and observedGeneration and True for the Available condition, which a script can compare directly. The filter [?(@.type=="Available")] selects a condition by its type instead of its position, which matters because the order of conditions is not guaranteed. custom-columns prints a table with exactly the columns you named.

06

Try it in the lab terminal

Look up the Deployment fields and let kubectl generate a scaffold, then apply a hand-written manifest that contains a one-letter typo and watch the API server reject it. After fixing the typo with sed, read back what the server stored. Finally change the spec through the file, apply it again, and query generation, a condition and pod placement with jsonpath and custom columns.

bash
kind create cluster
kubectl explain deployment.spec
kubectl create deployment web --image=nginx:1.27 --replicas=2 --dry-run=client -o yaml
cat > web.yaml <<'EOF'
apiVersion: apps/v1
kind: Deployment
metadata:
  name: web
  labels:
    app: web
  annotations:
    team.example.com/owner: payments
spec:
  replicas: 2
  selector:
    matchLabels:
      app: web
  template:
    metadata:
      labels:
        app: web
    spec:
      containers:
      - name: nginx
        imagee: nginx:1.27
EOF
kubectl apply -f web.yaml
sed -i 's/imagee:/image:/' web.yaml
kubectl apply -f web.yaml
kubectl rollout status deploy/web
kubectl get deployment web -o yaml
sed -i 's/replicas: 2/replicas: 3/' web.yaml
kubectl apply -f web.yaml
kubectl rollout status deploy/web
kubectl get deployment web -o jsonpath='{.metadata.generation} {.status.observedGeneration}{"\n"}'
kubectl get deployment web -o jsonpath='{.status.conditions[?(@.type=="Available")].status}{"\n"}'
kubectl get pods -o custom-columns=NAME:.metadata.name,PHASE:.status.phase,NODE:.spec.nodeName
Read the code

explain deployment.spec lists replicas, selector, template and strategy, and the dry-run prints a Deployment without creating it. The first apply fails with Error from server (BadRequest) ... strict decoding error: unknown field "spec.template.spec.containers[0].imagee", and nothing is created. After the fix, -o yaml shows what the server added: uid, resourceVersion, generation: 1, a RollingUpdate strategy with 25% maxSurge and maxUnavailable, and a status block you never wrote. Applying the edited file prints configured; generation and observedGeneration then both read 2, Available is True, and custom-columns lists each web-<hash>-<id> pod as Running on kind-control-plane.

TAKE THIS WITH YOU

Every object is apiVersion, kind, metadata, spec and status: you own the spec, controllers own the status. Scaffold with --dry-run=client -o yaml, look fields up with kubectl explain, let strict validation catch typos, and read state with jsonpath rather than by eye.

Check your understanding

You apply a Deployment whose container spec contains readinessprobe: with a lower-case p. What does kubectl apply do with default settings?

Go to the source

Progress stays in this browser. No account needed.