kubernetes kubernetes/cka

3. Interacting with Kubernetes

Core Idea

kubectl create makes an object once, apply declaratively converges a cluster to a manifest you can re-run, and patch edits fields of something that already exists.

  • create: one-shot and imperative, builds a brand new object and fails if it is already there.
  • apply: declarative upsert from a file, safe to run repeatedly as the desired state.
  • patch: modify specific fields of an existing object with a chosen patch type.

Kubectl create

Creates a brand new objects. (One shot, imperative).

kubectl create -f deploy.yaml
kubectl create deployment nginx --image=nginx:1.25

Key characteristics:

Tip

Quick, one-off object creation, scripting, or scaffolding a manifest (kubectl create deployment ... --dry-run=client -o yaml is a common trick to generate a starting YAML).

Kubectl apply

What it does: Declaratively reconciles the live object to match your YAML — creates it if missing, updates it if it exists, and computes a merge/diff (client-side or server-side, as discussed earlier).

kubectl apply -f deploy.yaml
kubectl apply --server-side -f deploy.yaml

Key characteristics:

  • Idempotent — you can run it repeatedly with the same file and get the same result.
  • Handles both create and update in one command.
  • Understands “desired state” over time — tracks what fields you own (via annotation in CSA, or managedFields in SSA) so it knows what to remove if you delete a field from your YAML.
  • This is the only one of the three that can remove fields that were previously set but are no longer in your manifest.

Use case: The standard for GitOps and declarative infrastructure — “this YAML file is the source of truth, make the cluster match it,” repeatedly, forever.

kubectl patch

What it does: Directly modifies specific fields of an existing object, without touching the rest.

kubectl patch deployment demo -n ssa-demo -p '{"spec":{"replicas":5}}'
 
# or with a patch type
kubectl patch deployment demo --type=json \
  -p '[{"op": "replace", "path": "/spec/replicas", "value": 5}]'

Key characteristics:

  • Fails if the object doesn’t exist — it only modifies, never creates.
  • You specify a partial payload — just the fields you want to change.
  • No concept of “desired state” tracking — it’s a surgical, one-time strike on specific fields.
  • Supports different patch strategies:
    • Strategic merge patch (default for built-in types) — smart about merging arrays/maps
    • JSON merge patch (--type=merge) — simpler, RFC 7386 semantics
    • JSON patch (--type=json) — explicit add/remove/replace operations on exact paths

Use case: Quick, targeted fixes — bump replicas, add a label, toggle a flag — without touching or even having the full manifest on hand.