Sub topic 1
Declarative APIs and desired state
Prerequisites
This chapter assumes you can do the following:
- Run
kubectl applyandkubectl getagainst a cluster. - Read Deployment and Pod manifests.
- Tell
specfromstatusin a manifest. - Use labels and selectors.
Imperative versus declarative
An imperative API takes commands, such as "start three Pods". A declarative API takes a description of the result you want, such as "three Pods should exist". Kubernetes is declarative. You store an object that describes the desired state, and the system works to make reality match it.
Compare the two styles:
# Imperative: you issue a step
kubectl scale deployment web --replicas=3
# Declarative: you submit the end state and let Kubernetes work out the steps
kubectl apply -f web.yamlBoth commands can reach the same result. The declarative form is easier to keep in version control and to re-run. Running it twice does no harm, because the second run finds nothing to change.
Desired state and observed state
Every Kubernetes object separates two things:
specis what you want. You write it.statusis what the system observes. Controllers write it.
apiVersion: apps/v1
kind: Deployment
metadata:
name: web
spec:
replicas: 3
selector:
matchLabels:
app: web
template:
metadata:
labels:
app: web
spec:
containers:
- name: web
image: nginx:1.27After you apply this, the API server stores the object. It does not start any containers itself. It validates the object, persists it, and makes it visible to clients. Other components read the object and act on it.
The API server as a record of intent
The API server is a store of intent with a consistent REST interface. Clients create, read, update, delete and watch objects. A watch is a long-lived request that streams changes, so a component hears about an edit without polling. Controllers rely on watches to react to new intent.
The controller in this diagram is the subject of the next chapter. For now, keep in mind that the declarative model only works because something keeps comparing the two states.
Why this matters for custom APIs
Because the model is declarative, you can add your own object types and get the same behavior for free. You get storage, validation, authorization, watches and kubectl support. Later chapters build a WebApp type on this foundation. A custom type is only a record of intent until a controller acts on it.
Exercise
You run kubectl apply -f web.yaml twice with no edits in between. Why is this safe, and which part of the object tells you whether the cluster has caught up with your intent?
Show answer
The manifest describes an end state, not a step. On the second run the stored desired state already matches, so there is nothing to change. The status field, which controllers write, shows whether the observed state has reached the desired state in spec.