Imperative commands and declarative apply

Intermediate · 36 min

kubectl create, scale and set against kubectl apply: the three ways to manage objects, how apply's three-way merge decides what to change, and where it bites.

Before thiskubectl, kubeconfig and contextsThe Kubernetes API and object model

CNCF [Cloud Native Computing Foundation] · 36 min

Imperative commands and declarative apply

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by CNCF [Cloud Native Computing Foundation]Report a problem with this video
Not started
Set this lesson's status

What you'll learn

  • Imperative commands (create, scale, set, edit) say what to do now. Declarative apply says what should exist and lets kubectl work out the change. Files in Git make the second reviewable and repeatable.
  • kubectl create --dry-run=client -o yaml is the quickest way to write a correct starting manifest.
  • Client-side apply stores your last applied file in an annotation and does a three-way merge of that, your new file and the live object.
  • A field you remove from your file is deleted from the live object. A field you never put in the file, set by someone else, is left alone.
  • kubectl diff shows exactly what an apply would change, computed by the server, before you run it.
  • Don't mix: a field both in your file and changed imperatively is reset at the next apply, which is why an HPA-managed Deployment should not set replicas in its manifest.

Two ways to give instructions

There are two ways to get a kitchen to produce dinner. You can stand at the pass calling out orders: “fire two steaks, now plate them, now add sauce”. Or you can hand over a menu and a booking sheet and let the kitchen work out what to cook. The first is fast for one dish and impossible to reproduce tomorrow. The second needs more writing up front, but anyone can read it, review it and run it again.

kubectl offers both styles. Imperative commands say what to do right now. Declarative configuration says what should exist, and leaves kubectl and the API server to work out the change. Most teams use both, and most surprises come from where they meet.

Three techniques, really

The Kubernetes docs name three, not two:

Technique Example Record of intent
Imperative commands kubectl create deployment shop --image=nginx:1.29 None
Imperative object configuration kubectl create -f shop.yaml, kubectl replace -f shop.yaml The file, but each command replaces or creates whole objects
Declarative object configuration kubectl apply -f shop/ The files, merged into the live objects

Imperative commands are perfect for exploration, one-off debugging and the CKA exam. Their weakness is that nothing records what you did. Imperative object configuration (create -f, replace -f) uses files but replaces whole objects, so a field someone else set, such as a sidecar an admission webhook injected, gets wiped. Declarative apply is what Git-driven workflows use.

The imperative commands are also the best manifest generator there is:

$ kubectl create deployment shop --image=nginx:1.29 --replicas=3 --dry-run=client -o yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  labels:
    app: shop
  name: shop
spec:
  replicas: 3
  selector:
    matchLabels:
      app: shop
  strategy: {}
  template:
    metadata:
      labels:
        app: shop
    spec:
      containers:
      - image: nginx:1.29
        name: nginx
        resources: {}
status: {}

Delete the empty strategy, resources and status, and you have a clean file to commit.

How apply decides what to change

kubectl apply by default is client-side apply. It has to answer a hard question: when your file lacks a field that the live object has, did you remove it on purpose, or did someone else add it? To answer, it remembers what you applied last time, in an annotation on the object:

kubectl.kubernetes.io/last-applied-configuration:
  {"apiVersion":"apps/v1","kind":"Deployment","metadata":{"annotations":{},"labels":{"app":"shop"},
   "name":"shop","namespace":"default"},"spec":{"replicas":3,...}}

Each apply then does a three-way merge of three versions:

  • Your new file: fields here are set to your values.
  • The last-applied annotation: fields that were here but are now missing from your file are deleted.
  • The live object: fields in neither of the above are left exactly as they are.

It sends the result as a patch, using strategic merge patch for built-in types so lists such as containers merge by name instead of being replaced wholesale.

Watching the merge in the lab

After applying the file above, three imperative changes were made on top, as people do during an incident:

kubectl scale deploy shop --replicas=5
kubectl set env deploy/shop LOG_LEVEL=debug
kubectl annotate deploy shop owner=team-a

Then the file’s image was bumped to nginx:1.30. kubectl diff asks the server to compute the result of an apply without saving it, and shows the difference:

-  replicas: 5
+  replicas: 3
...
-        image: nginx:1.29
+        image: nginx:1.30

(The diff was trimmed to its changed lines, plus the generation bump.) After kubectl apply -f shop.yaml:

replicas=3 image=nginx:1.30 env=[{"name":"LOG_LEVEL","value":"debug"}] owner=team-a

replicas was in the file, so the file won and the incident’s scale-up was undone. The env var and the annotation were never in the file or the last-applied record, so apply left them alone.

Now the classic trap. The live Deployment was scaled to 6, and the replicas: 3 line was deleted from the file, intending “stop managing replicas”. The diff:

-  replicas: 6
+  replicas: 1

The field was in last-applied and is now missing, so apply removes it, and the API server’s default of 1 takes over. Applying that took the Deployment from six replicas to one. After that apply, the annotation no longer mentions replicas, so a later kubectl scale --replicas=4 survived the next apply untouched. Removing a field you own is a two-step dance; kubectl diff before every apply is how you see it coming.

Mixing create and apply

Objects made imperatively have no annotation. Apply copes, with a warning:

Warning: resource configmaps/legacy is missing the kubectl.kubernetes.io/last-applied-configuration
annotation which is required by kubectl apply. ... The missing annotation will be patched automatically.

On that first apply it has no record of your previous intent, so it cannot delete anything. Use kubectl create --save-config if you must create imperatively and apply later.

Pruning, and the limits of client-side apply

Apply only touches objects in the files you give it. Delete worker.yaml from Git and the Deployment stays in the cluster. kubectl apply --prune tries to fix that, but kubectl v1.37’s own help still marks it alpha, with a newer ApplySet-based mode behind KUBECTL_APPLYSET=true. In practice, Helm, Kustomize with a GitOps tool such as Argo CD, or the packaging survey’s tools track the set of objects for you.

Client-side apply has deeper limits too. The annotation can be large, only one “applier” is remembered, and two tools applying the same object overwrite each other silently. Server-side apply, next, moves the merge into the API server and tracks ownership per field.

About the video

The embed is Aaron Levy’s KubeCon talk “kubectl apply, and The Dark Art of Declarative Object Management” (CNCF, December 2017, 36 minutes). Its abstract promises the inner workings of kubectl apply: how it interacts with imperative commands such as set, scale and edit, the different patch strategies, how merges are calculated, and the gotchas, ending on why an app can be “a declarative base, with replicas driven imperatively, by an autoscaler that is declaratively configured”. There are no chapters, so it was judged from that abstract. Client-side apply works the same way today, but the talk predates server-side apply, which became GA in 1.22 and is covered next. English was judged from the English title, abstract and caption track; there is no audio-track metadata. Drewbernetes’ beginner video in deeper is the gentler introduction to the two styles.

What was run: every command and output above ran against a local v1.37.3 API server with kubectl v1.37.3, whose nodes run no containers, on 2026-11-28. The prune status is from that kubectl’s apply --help.

Where this fits

Next, the version of apply that lives in the API server: server-side apply and field ownership.

Check yourself

  1. 01Someone ran kubectl scale deploy shop --replicas=6 during an incident. Your manifest says replicas: 3. What happens at the next kubectl apply?

    replicas goes back to 3. The field is in your file, so apply treats your value as the truth and overwrites the live 6. If an autoscaler or humans own replicas, leave it out of the manifest.

  2. 02You delete the replicas line from the manifest, which you had previously applied with replicas: 3. The live Deployment has 6. What does apply do?

    It removes the field, because it was in the last-applied annotation and is now missing from your file, so apply concludes you want it gone. The API server then defaults it to 1. Run kubectl diff first and you see replicas going from 6 to 1.

  3. 03kubectl set env added LOG_LEVEL=debug to a Deployment. Your manifest has never mentioned env. Does the next apply remove it?

    No. The field is in neither your file nor the last-applied annotation, so the three-way merge has no opinion and keeps the live value. That is also how drift survives quietly; server-side apply and GitOps tools make it visible.

  4. 04What warning do you get when you kubectl apply an object that was made with kubectl create, and why does it matter?

    That the last-applied-configuration annotation is missing and will be patched in. Until then apply had no record of what you previously declared, so it cannot tell which live fields you meant to delete. Create declaratively from the start, or use create --save-config.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark