Skip to content
Kubernetes tools · Chapter 4 of 20 Day 2: Changes Without Surprises

Day 2: Changes Without Surprises

Goal: See changes beforehand and apply them deliberately: diff and --dry-run=server, Server-Side Apply with field managers, the three patch types, kustomize without an extra tool, checking permissions with auth can-i and --as · Duration: approx. 75 min · Prerequisite: Day 1

Briefing

  • Most incidents start with a change. The tools of this day answer three questions before something breaks: What changes? Who else changes this object? Am I (or a service) allowed to do this at all?
  • All of it is part of kubectl itself: diff, --dry-run=server, apply --server-side, patch, kustomize (built in for years) and auth.
Question Tool
What would my manifest change in the cluster? kubectl diff
Would the API server accept this? --dry-run=server
Who owns this field? Server-Side Apply, --show-managed-fields
How do I change just one value? kubectl patch (strategic, merge, json)
How do I keep variants without copies? kubectl apply -k
Is this ServiceAccount allowed to do this? kubectl auth can-i --as

Drill 1: Look First, Then Apply

A modified copy of the manifest from Day 0: four instead of three frontend Pods and more memory. kubectl diff compares with the live state and shows only what would change:

mkdir -p ~/werkzeuge/tag02 && cd ~/werkzeuge/tag02
sed "s/replicas: 3/replicas: 4/; s/memory: 64Mi/memory: 96Mi/" ~/werkzeuge/tag00/laden.yaml > laden-neu.yaml
kubectl diff -f laden-neu.yaml; echo "exit $?"

Expected (shortened):

diff -u -N /tmp/LIVE-1298063516/apps.v1.Deployment.laden.web /tmp/MERGED-3844111286/apps.v1.Deployment.laden.web
-  generation: 3
+  generation: 4
-  replicas: 3
+  replicas: 4
         resources:
           limits:
-            memory: 64Mi
+            memory: 96Mi
exit 1

Exit code 1 means “there are differences”, 0 means “nothing to do”. In a pipeline, this is the place for an approval. For single commands, there is --dry-run=server: the API server checks everything (schema, admission, quotas) but stores nothing:

kubectl -n laden create deployment test --image=nginx:1.30.7-alpine --dry-run=server -o name
kubectl -n laden get deploy test

Expected:

deployment.apps/test
Error from server (NotFound): deployments.apps "test" not found

--dry-run=client, in contrast, only checks locally and notices nothing of admission rules.

Save your progress? Sign up for free

Drill 2: Who Owns the Field?

With Server-Side Apply, the API server remembers for each field which field manager set it. Two teams maintain the same ConfigMap:

cd ~/werkzeuge/tag02
cat > aktion.yaml <<'EOF'
apiVersion: v1
kind: ConfigMap
metadata:
  name: aktion
  namespace: laden
data:
  RABATT: "10"
  BANNER: "Herbstaktion"
EOF
kubectl apply --server-side --field-manager=team-shop -f aktion.yaml
sed 's/"10"/"20"/' aktion.yaml > aktion-marketing.yaml
kubectl apply --server-side --field-manager=team-marketing -f aktion-marketing.yaml; echo "exit $?"

Expected:

configmap/aktion serverside-applied
error: Apply failed with 1 conflict: conflict with "team-shop": .data.RABATT
Please review the fields above--they currently have other managers. Here
are the ways you can resolve this warning:
* If you intend to manage all of these fields, please re-run the apply
  command with the `--force-conflicts` flag.
* If you do not intend to manage all of the fields, please edit your
  manifest to remove references to the fields that should keep their
  current managers.
* You may co-own fields by updating your manifest to match the existing
  value; in this case, you'll become the manager if the other manager(s)
  stop managing the field (remove it from their configuration).
See https://kubernetes.io/docs/reference/using-api/server-side-apply/#conflicts
exit 1

The conflict is the whole point: marketing would have silently overwritten the shop team’s discount (RABATT). If you really want that, you take over the field explicitly:

kubectl apply --server-side --field-manager=team-marketing --force-conflicts -f aktion-marketing.yaml
kubectl -n laden get cm aktion -o yaml --show-managed-fields | sed -n '/managedFields/,/name: aktion/p' | grep -E 'manager|f:RABATT|f:BANNER|operation'

Expected:

configmap/aktion serverside-applied
        f:BANNER: {}
        f:RABATT: {}
    manager: team-marketing
    operation: Apply
        f:BANNER: {}
    manager: team-shop
    operation: Apply

RABATT now belongs only to marketing, BANNER to both, because both set the same value. GitOps tools (Argo CD, Flux, Day 12) work exactly this way: each has its own field manager, and conflicts with manual changes become visible instead of being silently overwritten.

Save your progress? Sign up for free

Drill 3: Three Ways to Patch

kubectl patch changes individual fields without a manifest. There are three types, and the differences show up with lists. First strategic merge (the default): containers are merged by their name.

kubectl -n laden patch deploy web -p '{"spec":{"template":{"spec":{"containers":[{"name":"nginx","env":[{"name":"MODUS","value":"herbst"}]}]}}}}'
kubectl -n laden get deploy web -o jsonpath='{.spec.template.spec.containers[0].image} {.spec.template.spec.containers[0].env}{"\n"}'

Expected:

deployment.apps/web patched
nginx:1.30.7-alpine [{"name":"MODUS","value":"herbst"}]

The environment variable is there, the image unchanged. The same patch as a JSON merge patch (RFC 7386):

kubectl -n laden patch deploy web --type=merge -p '{"spec":{"template":{"spec":{"containers":[{"name":"nginx","env":[{"name":"MODUS","value":"winter"}]}]}}}}'; echo "exit $?"

Expected:

The Deployment "web" is invalid: spec.template.spec.containers[0].image: Required value
exit 1

Merge patch knows no keys in lists: it replaces the whole container list with one container without an image. Fortunately, the API server rejects that. For precise changes, there is JSON Patch (RFC 6902) with a path and an operation:

kubectl -n laden patch deploy web --type=json -p '[{"op":"replace","path":"/spec/template/spec/containers/0/env/0/value","value":"winter"}]'
kubectl -n laden get deploy web -o jsonpath='{.spec.template.spec.containers[0].env}{"\n"}'
kubectl -n laden patch deploy web --type=json -p '[{"op":"remove","path":"/spec/template/spec/containers/0/env"}]'
kubectl -n laden rollout status deploy/web --timeout=120s | tail -1

Expected:

deployment.apps/web patched
[{"name":"MODUS","value":"winter"}]
deployment.apps/web patched
deployment "web" successfully rolled out
Type Lists Good for
strategic (default) merged by key (e.g. name) Kubernetes objects, most cases
merge are replaced CRDs (do not know strategic), simple maps
json path with index, add/replace/remove/test precise changes, deleting a field

Save your progress? Sign up for free

Drill 4: Variants with kustomize

An autumn sale (aktion) needs a second variant of the frontend: two replicas, a different image tag, a label. kustomize builds this from a base and an overlay, without a copy and without a template language. kubectl ships with it:

cd ~/werkzeuge/tag02 && mkdir -p basis aktion
cat > basis/web.yaml <<'EOF'
apiVersion: apps/v1
kind: Deployment
metadata:
  name: web-aktion
spec:
  replicas: 1
  selector:
    matchLabels: {app: web-aktion}
  template:
    metadata:
      labels: {app: web-aktion}
    spec:
      containers:
      - name: nginx
        image: nginx:1.30.7-alpine
EOF
cat > basis/kustomization.yaml <<'EOF'
resources:
- web.yaml
EOF
cat > aktion/kustomization.yaml <<'EOF'
resources:
- ../basis
namespace: laden
labels:
- pairs: {aktion: herbst}
  includeSelectors: false
replicas:
- name: web-aktion
  count: 2
images:
- name: nginx
  newTag: 1.29.6-alpine
EOF
kubectl version --client | grep -i kustomize
kubectl kustomize aktion

Expected:

Kustomize Version: v5.8.1
apiVersion: apps/v1
kind: Deployment
metadata:
  labels:
    aktion: herbst
  name: web-aktion
  namespace: laden
spec:
  replicas: 2
  selector:
    matchLabels:
      app: web-aktion
  template:
    metadata:
      labels:
        app: web-aktion
    spec:
      containers:
      - image: nginx:1.29.6-alpine
        name: nginx

includeSelectors: false is important: otherwise the label also ends up in the selector, and a selector is immutable after creation. Apply with -k instead of -f:

kubectl apply -k aktion
kubectl -n laden rollout status deploy/web-aktion --timeout=120s | tail -1
kubectl -n laden get deploy web-aktion -L aktion -o wide | cut -c1-140

Expected:

deployment.apps/web-aktion created
deployment "web-aktion" successfully rolled out
NAME         READY   UP-TO-DATE   AVAILABLE   AGE   CONTAINERS   IMAGES                SELECTOR         AKTION
web-aktion   2/2     2            2           13s   nginx        nginx:1.29.6-alpine   app=web-aktion   herbst

kubectl diff -k aktion works the same way. When Helm instead of kustomize? As soon as others are supposed to install a package with parameters (Day 12).

Save your progress? Sign up for free

Drill 5: Is It Allowed to Do That?

Who am I in the first place, and what is the ServiceAccount api from Day 0 allowed to do?

kubectl auth whoami
SA=system:serviceaccount:laden:api
for v in "list pods -A" "get secrets -n laden" "delete pods -n laden" "list configmaps -n kube-system"; do echo "$v: $(kubectl auth can-i $v --as=$SA)"; done

Expected:

ATTRIBUTE                                           VALUE
Username                                            kubernetes-admin
Groups                                              [kubeadm:cluster-admins system:authenticated]
Extra: authentication.kubernetes.io/credential-id   [X509SHA256=e26bcce1f4664a4876fb6773603a91c6d19e4875a1cf0f9e6f3a7f6c90777567]
list pods -A: yes
get secrets -n laden: no
delete pods -n laden: no
list configmaps -n kube-system: yes

--as uses impersonation: you, as admin, ask the API server what it would allow another user to do. This also works with real commands:

kubectl get pods -n lager --as=$SA
kubectl get secret db-zugang -n laden --as=$SA
kubectl auth can-i --list -n laden --as=$SA | grep -E 'Resources|^pods |^secrets|^configmaps |^deployments.apps'

Expected (Pod name will differ for you):

NAME                      READY   STATUS    RESTARTS   AGE
packer-68485bc749-ksh4x   1/1     Running   0          6m47s
Error from server (Forbidden): secrets "db-zugang" is forbidden: User "system:serviceaccount:laden:api" cannot get resource "secrets" in API group "" in the namespace "laden"
Resources                                       Non-Resource URLs                      Resource Names   Verbs
configmaps                                      []                                     []               [get list watch]
pods                                            []                                     []               [get list watch]
deployments.apps/scale                          []                                     []               [get list watch]
deployments.apps/status                         []                                     []               [get list watch]
deployments.apps                                []                                     []               [get list watch]

The built-in role view deliberately leaves out Secrets. Still, the binding from Day 0 is too broad: the API of a shop can read all Pods and all ConfigMaps of the cluster, including in kube-system. Who in the cluster is allowed to do anything at all is not something can-i answers; for that you need the other direction (Day 4, who-can).

Save your progress? Sign up for free

Exercise: Speed Drills

  1. Under which user name are you working? Only the name. Target time: 20 s
  2. Is the ServiceAccount api allowed to read Secrets in the namespace laden? Target time: 20 s
  3. Would the API server scale web to 5 replicas? Check without scaling. Target time: 45 s

Solution

kubectl auth whoami -o jsonpath='{.status.userInfo.username}{"\n"}'
kubectl auth can-i get secrets -n laden --as=system:serviceaccount:laden:api
kubectl -n laden scale deploy web --replicas=5 --dry-run=server -o jsonpath='{.spec.replicas}{"\n"}'
kubectl -n laden get deploy web -o jsonpath='{.spec.replicas}{"\n"}'

Expected:

kubernetes-admin
no
5
3

Save your progress? Sign up for free

Challenge

A colleague (user kollege) should be allowed to restart the packer in the namespace lager, and nothing else. The platform team’s first attempt:

kubectl -n lager create role neustart --verb=delete --resource=pods
kubectl -n lager create rolebinding kollege-neustart --role=neustart --user=kollege
kubectl -n lager rollout restart deploy/packer --as=kollege
kubectl -n lager delete pod -l app=packer --as=kollege --wait=false

Expected:

role.rbac.authorization.k8s.io/neustart created
rolebinding.rbac.authorization.k8s.io/kollege-neustart created
Error from server (Forbidden): deployments.apps "packer" is forbidden: User "kollege" cannot get resource "deployments" in API group "apps" in the namespace "lager"
Error from server (Forbidden): pods is forbidden: User "kollege" cannot list resource "pods" in API group "" in the namespace "lager"

Both fail, although delete pods is allowed. Why, and which permissions does the colleague need at minimum for rollout restart?

Hint: What does rollout restart do to the Deployment, and what does delete -l do before deleting?

Solution

  • rollout restart does not delete any Pods. It reads the Deployment and sets an annotation with the timestamp in the Pod template; for that it needs get and patch on deployments.
  • delete pod -l … first has to list the matching Pods and therefore additionally needs list.

The smallest matching role for the restart:

kubectl -n lager create role neustart-deploy --verb=get,patch --resource=deployments
kubectl -n lager create rolebinding kollege-neustart-deploy --role=neustart-deploy --user=kollege
kubectl -n lager rollout restart deploy/packer --as=kollege
for v in "patch deployments -n lager" "patch deployments -n laden" "delete pods -n laden"; do echo "$v: $(kubectl auth can-i $v --as=kollege)"; done
kubectl -n lager rollout status deploy/packer --timeout=60s | tail -1

Expected:

role.rbac.authorization.k8s.io/neustart-deploy created
rolebinding.rbac.authorization.k8s.io/kollege-neustart-deploy created
deployment.apps/packer restarted
patch deployments -n lager: yes
patch deployments -n laden: no
delete pods -n laden: no
deployment "packer" successfully rolled out

He does not need the role neustart (delete pods) for this at all. But patch is not entirely free of side effects: whoever may patch Deployments can also change the image. For “only restart”, RBAC has no finer level; admission policies solve that.

Save your progress? Sign up for free

Checkpoint

First clean up (see below), then:

kubectl -n laden get deploy
kubectl diff -f ~/werkzeuge/tag00/laden.yaml >/dev/null; echo "diff exit $?"

Expected:

NAME    READY   UP-TO-DATE   AVAILABLE   AGE
api     2/2     2            2           7m11s
cache   1/1     1            1           7m11s
web     3/3     3            3           7m11s
diff exit 0

The shop matches the manifest from Day 0 exactly again.

Clean-up

cd ~/werkzeuge/tag02
kubectl delete -k aktion
kubectl -n laden delete cm aktion
kubectl -n lager delete role neustart neustart-deploy
kubectl -n lager delete rolebinding kollege-neustart kollege-neustart-deploy

Expected:

deployment.apps "web-aktion" deleted from laden namespace
configmap "aktion" deleted from laden namespace
role.rbac.authorization.k8s.io "neustart" deleted from lager namespace
role.rbac.authorization.k8s.io "neustart-deploy" deleted from lager namespace
rolebinding.rbac.authorization.k8s.io "kollege-neustart" deleted from lager namespace
rolebinding.rbac.authorization.k8s.io "kollege-neustart-deploy" deleted from lager namespace

Interview Note

  • Client-side or Server-Side Apply? Server-Side Apply manages field ownership on the server, detects conflicts between tools and needs no last-applied annotation. For several parties (human, CI, operator), it is the better choice.
  • Why does a merge patch fail on a container list? JSON Merge Patch replaces lists entirely. Strategic merge knows the key name and merges; JSON Patch addresses by index.
  • How do I check the permissions of a ServiceAccount? kubectl auth can-i <verb> <resource> --as system:serviceaccount:<ns>:<name>, with --list for the whole list.

Enterprise Note

  • Make kubectl diff a mandatory step in every pipeline that applies manifests, and write the output into the merge request. Reviewers then see changes to the cluster, not just to the text.
  • Impersonation (--as) is itself a permission (impersonate). It belongs to admins only and is recorded in the audit log with both identities, the real user and the assumed one.
  • Manual changes to the cluster (patch, scale, edit) are drift in GitOps environments. Server-Side Apply makes them visible, Argo CD and Flux revert them (Day 12).

Contents

More