Skip to content
Kubernetes tools · Chapter 18 of 20 Appendix A: Cheat Sheet

Appendix A: Cheat Sheet

The most important commands, switches and keys from Days 0 to 15, sorted by topic. The days are in parentheses. The names are those from the lab: cluster kind-werkzeuge, namespaces laden (shop) and lager (warehouse), helper Pods werkbank (workbench) and netshoot, ServiceAccounts api, kasse (checkout) and betrachter (viewer).

Tool Version Day
kind / Kubernetes / kubectl / Helm v0.33.0 / v1.37.0 / v1.37.2 / v4.3.2 0
cilium-cli / Cilium v0.20.3 / 1.20.5 0
Kustomize (in kubectl) v5.8.1 2
kubectx and kubens / kube-ps1 / kubie 0.11.0 / v1.0.0 / 0.28.0 3
Krew v0.5.0 4
tree / neat / view-secret / who-can v0.6.0 / v2.0.4 / v0.17.0 / v0.4.0 4
access-matrix / resource-capacity / images v0.5.0 / v0.8.0 / v0.6.5 4
k9s v0.51.0 5
Headlamp (chart and app) / Freelens 0.46.0 / 2.1.0 6
stern 1.35.0 7
netshoot / Hubble CLI v0.17 / v1.20.4 8
Popeye / Pluto v0.22.1 / v5.24.5 9
metrics-server / VPA / Goldilocks (charts) 3.14.0 / 5.2.0 / 11.3.1 9
kubeconform / kube-linter / kube-score / Polaris v0.8.0 / v0.8.3 / v1.20.0 / v10.2.6 10
Trivy / kube-bench / Kubescape / rbac-tool v0.76.2 / v0.16.0 / v4.0.21 / v1.20.0 11
helm-diff / Argo CD / Flux v3.15.15 / v3.6.2 / v2.10.1 12
k3d (k3s inside) / ctlptl v5.9.0 (v1.35.5) / v0.9.6 13
Go / client-go, cli-runtime, api / cobra 1.27.4 / v0.37.2 / v1.10.2 14

kubectl Queries (Days 0, 1)

kubectl explain deployment.spec.strategy.rollingUpdate.maxSurge | head -12
kubectl explain deployment --recursive | less
kubectl get pods -A -l 'app in (web,api,cache,packer)' \
  -o custom-columns=NS:.metadata.namespace,POD:.metadata.name,KNOTEN:.spec.nodeName,IMAGE:.spec.containers[0].image
kubectl get pods -A -o jsonpath='{range .items[?(@.spec.containers[0].securityContext.privileged==true)]}{.metadata.namespace}/{.metadata.name}{"\n"}{end}'
kubectl get pods -A -o json | jq -r '.items[]
  | select(.metadata.namespace=="laden" or .metadata.namespace=="lager")
  | select(any(.spec.containers[]; .resources.limits == null))
  | "\(.metadata.namespace)/\(.metadata.name)"'
kubectl get pods -A -o jsonpath='{range .items[*]}{range .spec.containers[*]}{.image}{"\n"}{end}{end}' | sort | uniq -c | sort -rn | head -8
kubectl get pods -A -o json | jq -r '[.items[].spec.containers[].image] | group_by(.) | map("\(length) \(.[0])") | .[]' | sort -rn | head -3
kubectl -n laden get events --sort-by=.lastTimestamp | tail -4 | cut -c1-150
kubectl get pods -A --field-selector=status.phase!=Running,status.phase!=Succeeded
kubectl get pods -A --field-selector spec.nodeName=werkzeuge-worker -o name | head -5
kubectl -n laden wait --for=jsonpath='{.status.readyReplicas}'=4 deploy/web --timeout=60s
kubectl -n laden get secret db-zugang -o jsonpath='{.data.DB_USER}' | base64 -d; echo
kubectl get nodes -o custom-columns=NAME:.metadata.name,CPU:.status.capacity.cpu,MEM:.status.capacity.memory
kubectl get node werkzeuge-worker -o jsonpath='{.status.conditions[?(@.type=="Ready")].message}{"\n"}'
Rule Day
JSONPath for single values and simple filters, jq as soon as “any”, “all”, grouping or counting comes in 1
A JSONPath filter on containers[0] only checks the first container; a sidecar slips through 1
Field selectors filter on the server but only know a few fields (Pods: status.phase, spec.nodeName, metadata.name) 1
--for=condition=Available means minimum availability, not “all replicas ready”; for rollouts kubectl rollout status 1
By default, events live for only one hour 1
A fresh node is NotReady as long as no CNI is running 0

Changes Without Surprises (Day 2)

kubectl diff -f laden-neu.yaml; echo "exit $?"
kubectl diff -k aktion
kubectl -n laden create deployment test --image=nginx:1.30.7-alpine --dry-run=server -o name
kubectl -n laden scale deploy web --replicas=5 --dry-run=server -o jsonpath='{.spec.replicas}{"\n"}'
kubectl apply --server-side --field-manager=team-shop -f aktion.yaml
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'
kubectl -n laden patch deploy web -p '{"spec":{"template":{"spec":{"containers":[{"name":"nginx","env":[{"name":"MODUS","value":"herbst"}]}]}}}}'
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 patch deploy web --type=json -p '[{"op":"remove","path":"/spec/template/spec/containers/0/env"}]'
kubectl version --client | grep -i kustomize
kubectl kustomize aktion
kubectl apply -k aktion
kubectl delete -k aktion
kubectl auth whoami
kubectl auth whoami -o jsonpath='{.status.userInfo.username}{"\n"}'
kubectl auth can-i get secrets -n laden --as=system:serviceaccount:laden:api
kubectl auth can-i --list -n laden --as=$SA | grep -E 'Resources|^pods |^secrets|^configmaps |^deployments.apps'
kubectl get secret db-zugang -n laden --as=$SA
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
Patch type Lists Good for
strategic (default) merged by key (e.g. name) Kubernetes objects, most cases
merge (--type=merge) are replaced CRDs (do not know strategic), simple maps
json (--type=json) path with index, add/replace/remove/test precise changes, deleting a field

kubectl diff exits with 1 if there are differences, with 0 if there are none. --dry-run=server checks schema, admission and quotas, --dry-run=client only locally. In kustomize labels, use includeSelectors: false, otherwise the label ends up in the immutable selector. rollout restart needs get and patch on deployments, delete pod -l … additionally needs list.

Contexts and kubeconfig (Day 3)

kubectl config get-contexts
kubectl config current-context
kubectl config view --minify -o jsonpath='{.clusters[0].cluster.server}{"\n"}'
kubectl config view --minify --flatten --context kubedrill > kubedrill.yaml
KUBECONFIG=kind.yaml:kubedrill.yaml kubectl config get-contexts
kubectl config use-context kind-werkzeuge
kubectx
kubectx kubedrill
kubectx -
kubectx -c
kubectx kurz=sehr-langer-name
kubens laden
kubens -
kubens -c
kubie ctx kind-werkzeuge -n laden
kubie info ctx
kubie info ns
kubie exec kubedrill default kubectl get nodes | head -2

Your own kubeconfig for a ServiceAccount, time-limited:

TOKEN=$(kubectl -n laden create token api --duration=1h)
SERVER=$(kubectl config view --minify -o jsonpath='{.clusters[0].cluster.server}')
kubectl config view --minify --raw -o jsonpath='{.clusters[0].cluster.certificate-authority-data}' | base64 -d > ca.crt
export KUBECONFIG=api.yaml
kubectl config set-cluster werkzeuge --server=$SERVER --certificate-authority=ca.crt --embed-certs
kubectl config set-credentials api --token=$TOKEN
kubectl config set-context api --cluster=werkzeuge --user=api --namespace=laden
kubectl config use-context api
unset KUBECONFIG

kube-ps1 in ~/.bashrc:

source ~/.kube-ps1.sh
KUBE_PS1_SYMBOL_ENABLE=false
PS1='$(kube_ps1) \$ '
kubectx/kubens kubie
Effect changes ~/.kube/config for all shells own kubeconfig per shell
Two clusters in two terminals trap made for it
Scripts specify --context/-n kubie exec

kubeoff hides the prompt display, kubeon shows it again. --flatten embeds certificates, --minify shows only the current context.

Krew and Plugins (Day 4)

kubectl krew version | head -3
kubectl krew search | wc -l
kubectl krew install tree neat view-secret who-can access-matrix resource-capacity images
kubectl krew list
kubectl krew upgrade
kubectl plugin list
kubectl tree deploy web -n laden
kubectl -n laden get deploy cache -o yaml | kubectl neat
kubectl view-secret db-zugang DB_PASSWORD -n laden; echo
kubectl view-secret db-zugang --all -n laden
kubectl who-can get secrets -n laden
kubectl who-can list pods -n lager | grep -E 'CLUSTERROLEBINDING|api-alles-lesen'
kubectl access-matrix --sa laden:api -n laden
kubectl access-matrix for secrets -n laden | head -12
kubectl resource-capacity
kubectl resource-capacity --pods -n laden | head -14
kubectl images -n laden | head -12
Question Plugin
What belongs to this Deployment? tree
What does the manifest look like without runtime clutter? neat
What is in this Secret, in plain text? view-secret
Who may read Secrets? who-can
What may this ServiceAccount do, at a glance? access-matrix
How full are the nodes (requests, limits)? resource-capacity
Which images run here? images

A plugin is an executable file kubectl-<name> in the PATH; hyphens in the command become underscores in the file name (view-secret → kubectl-view_secret). view-secret without a key and without --all waits for an interactive selection, so in scripts it waits forever.

k9s (Day 5)

k9s version -s
k9s info
k9s -n laden
k9s -n laden --readonly
Key or command Effect
:pods, :deploy, :svc, :dp (alias) switch view
0, 1, 2 … namespace: all, recently used
/text, /cache\|packer filter the list (also regular expressions), Esc clears it
Enter one level deeper: Deployment → Pods → containers
l, p logs, logs of the previous container
d, y, e, s describe, YAML, edit, shell
a, Ctrl-D, Ctrl-K attach, delete, kill
Shift-J, z jump to owner, sanitize
Shift-F, :pf forward a port, show forwards
:xray deploy laden tree of Deployments, Pods, containers, Secrets
Ctrl-S save the current list as CSV
? help, free shortcuts
:q or Ctrl-C quit
in the log view s, t, w, 0–5 autoscroll, timestamps, wrap, time range
in read-only mode o, f Show Node, Show PortForward
File or location Content
~/.config/k9s/plugins.yaml, hotkeys.yaml, aliases.yaml custom plugins, hotkeys, aliases
~/.local/state/k9s/k9s.log log, first place to look on “Plugins load failed!”
~/.local/state/k9s/screen-dumps/ CSV exports from Ctrl-S
~/.local/share/k9s/clusters/ per-context configuration (e.g. read-only)
plugins:
  neat:
    shortCut: Ctrl-Y
    description: YAML ohne Ballast
    scopes: [all]
    command: bash
    background: false
    args:
    - -c
    - kubectl get $RESOURCE_NAME $NAME -n $NAMESPACE --context $CONTEXT -o yaml | kubectl neat | less

[R] instead of [RW] at the top left means read-only. k9s uses capital letters such as Shift-N itself, for sorting.

Graphical User Interfaces (Day 6)

helm install headlamp headlamp/headlamp -n headlamp --create-namespace --version 0.46.0
kubectl get clusterrolebinding -o wide | grep -i headlamp
kubectl auth can-i "*" "*" --as=system:serviceaccount:headlamp:headlamp
kubectl -n headlamp create serviceaccount betrachter
kubectl create clusterrolebinding betrachter-view --clusterrole=view --serviceaccount=headlamp:betrachter
kubectl -n headlamp create token betrachter --duration=2h
kubectl -n headlamp port-forward --address 0.0.0.0 svc/headlamp 8080:80
helm upgrade headlamp headlamp/headlamp -n headlamp --version 0.46.0 --set clusterRoleBinding.create=false
docker run -d --name headlamp-lokal --network host \
  -v $PWD/betrachter.kubeconfig:/kc/config:ro \
  ghcr.io/headlamp-k8s/headlamp:v0.46.0 -kubeconfig /kc/config -port 4466
ssh -N -L 45811:127.0.0.1:45811 ubuntu@<IP-der-VM>

A UI has exactly the permissions of the account it talks with. Without clusterRoleBinding.create=false, the Headlamp chart binds its ServiceAccount to cluster-admin. The built-in role edit may read Secrets, view may not.

Logs and Debugging (Day 7)

stern --version
stern -n laden web --since 1m --no-follow
stern -n laden kasse --since 5m --no-follow --include ERROR 2>/dev/null
stern -n laden kasse --since 30s --no-follow --exclude INFO 2>/dev/null
stern -n laden kasse --since 2m --no-follow --include WARN --only-log-lines
stern -n laden kasse --tail 2 --no-follow --template '{{.PodName}} | {{.Message}}{{"\n"}}' 2>/dev/null
stern -n laden -l tier=backend --tail 1 --no-follow -E debugger 2>/dev/null
stern -n laden kasse --tail 1 --no-follow -o json 2>/dev/null | head -1
kubectl -n laden logs -l app=web --prefix --tail=1
kubectl -n laden get $P -o jsonpath='{.status.containerStatuses[0].state}{"\n"}'
kubectl -n laden logs $P --tail=3
kubectl -n laden logs $P --previous
kubectl -n laden get pods -l app=kasse -o custom-columns='POD:.metadata.name,NEUSTARTS:.status.containerStatuses[0].restartCount,EXIT:.status.containerStatuses[0].lastState.terminated.exitCode,ENDE:.status.containerStatuses[0].lastState.terminated.finishedAt'
kubectl -n laden rollout undo deploy/kasse
kubectl -n laden debug -it $A --image=busybox:1.37.0 --target=whoami -- sh
kubectl -n laden debug -i $A --image=busybox:1.37.0 --target=whoami --profile=general -- \
  sh -c 'ps; tr "\0" "\n" < /proc/1/environ | grep DB_; ls /proc/1/root/'
kubectl -n laden logs $A -c debugger-m8snk
kubectl -n laden get pod $A -o jsonpath='{range .spec.ephemeralContainers[*]}{.name} {.image} {.targetContainerName}{"\n"}{end}'
kubectl auth can-i patch pods/ephemeralcontainers -n laden --as=system:serviceaccount:laden:kasse
kubectl -n laden debug $K --copy-to=kasse-debug --container=kasse -- sleep 3600
kubectl debug node/werkzeuge-worker -i --image=busybox:1.37.0 --profile=sysadmin -- \
  chroot /host sh -c 'hostname; df -h /var | tail -1'
kubectl debug node/$N -i --image=busybox:1.37.0 --profile=sysadmin -- chroot /host crictl ps -a --name kasse
kubectl get pods -o name | grep node-debugger | xargs -r kubectl delete
Task Tool
Logs of many Pods live stern <regex> or stern -l <label>
Filter logs stern -i <regex>, -e <regex>
Logs of the crashed container kubectl logs --previous
Shell in a container without a shell kubectl debug -it <pod> --image=… --target=<container>
Rebuild a Pod with a different command kubectl debug <pod> --copy-to=<name> --container=… -- <command>
Look at a node kubectl debug node/<node> -it --image=… --profile=sysadmin

The kubelet keeps exactly one terminated predecessor per container. Exit code and reason are always in the status (state.terminated or lastState.terminated). --previous shows the container before, not the one that just died. An ephemeral container stays in the Pod until the Pod is replaced. The copy from --copy-to has no labels (--keep-labels would carry them over). --profile=sysadmin is privileged.

Network and Hubble (Day 8)

kubectl -n laden run netshoot --image=nicolaka/netshoot:v0.17 --restart=Never -- sleep infinity
kubectl -n laden exec netshoot -- dig +short web.laden.svc.cluster.local
kubectl -n laden exec netshoot -- dig +search +short api
kubectl -n laden exec netshoot -- cat /etc/resolv.conf
kubectl -n laden exec netshoot -- curl -s -m3 http://api:8080/
kubectl -n laden exec netshoot -- curl -s -m3 -o /dev/null -w "%{http_code}\n" http://api:8080/
kubectl -n laden exec netshoot -- nc -zv -w2 web 443
kubectl -n laden exec netshoot -- dig cache.laden.svc.cluster.local | grep status
kubectl -n laden exec netshoot -- sh -c "printf 'PING\r\n' | nc -w2 cache 6379"
kubectl -n laden get endpointslices -l kubernetes.io/service-name=api -o jsonpath='{.items[*].endpoints[*].targetRef.name}{"\n"}'
kubectl -n laden debug $W --image=nicolaka/netshoot:v0.17 --target=nginx --profile=netadmin \
  --container=sniffer -- tcpdump -i eth0 -nn -c 8 "tcp port 80 and host $BIP"
kubectl -n laden logs $W -c sniffer
kubectl cp -c sniffer laden/$W:/tmp/web.pcap web.pcap
cilium hubble port-forward
hubble status
hubble observe -n laden --verdict DROPPED --last 3
hubble observe --to-pod laden/api --protocol tcp --last 6 -o compact
hubble observe --from-label app=kasse --type policy-verdict --last 1 -o compact
hubble observe --from-pod laden/werkbank --to-label app=web --type policy-verdict --last 1 -o compact
hubble observe -n laden --verdict DROPPED --last 50 -o json | jq -r '.flow | [.source.pod_name, .destination.pod_name, .drop_reason_desc] | @tsv' | sort | uniq -c
kubectl -n kube-system port-forward --address 0.0.0.0 svc/hubble-ui 12000:80
kubectl -n laden patch networkpolicy api-nur-von-web --type=json \
  -p '[{"op":"add","path":"/spec/ingress/0/from/-","value":{"podSelector":{"matchLabels":{"app":"kasse"}}}}]'
Failure pattern Cause Confirm with
curl exit 28, 000: timeout NetworkPolicy drops hubble observe -n laden --verdict DROPPED
Connection refused target reached, nothing listening on the port kubectl -n laden get svc web
getaddrinfo … Try again, NXDOMAIN no Service with this name kubectl -n laden get svc
Service IP hangs, Pod IP works selector or targetPort does not match kubectl get endpointslices -l kubernetes.io/service-name=…

Order: name → address → port → permission. --to-pod expects namespace/prefix and does not combine with -n. --last applies per node. Two entries under from are an or, two labels in one podSelector an and. podSelector: {} without namespaceSelector means all Pods in the same namespace.

Cluster Hygiene (Day 9)

popeye -n laden --force-exit-zero
popeye -n laden -s svc --force-exit-zero
popeye -n laden -s svc -l error --force-exit-zero
popeye -A --force-exit-zero | grep -E "NETWORKPOLICIES|ROLEBINDINGS|SERVICEACCOUNTS"
popeye -n laden -f spinach.yaml -s po --force-exit-zero
helm install metrics-server metrics-server/metrics-server -n kube-system --version 3.14.0 --set "args={--kubelet-insecure-tls}"
kubectl top nodes
kubectl resource-capacity --util --sort cpu.util
kubectl resource-capacity -n laden --pods --util
helm install vpa fairwinds-stable/vpa -n vpa --create-namespace --version 5.2.0 \
  --set updater.enabled=false --set admissionController.enabled=false
helm install goldilocks fairwinds-stable/goldilocks -n goldilocks --create-namespace --version 11.3.1
kubectl label ns laden goldilocks.fairwinds.com/enabled=true
kubectl -n laden get vpa
kubectl -n laden get vpa goldilocks-kasse -o jsonpath='{.status.recommendation.containerRecommendations[0].target}{"\n"}'
kubectl -n goldilocks port-forward --address 0.0.0.0 svc/goldilocks-dashboard 8090:80
kubectl -n laden set resources deploy kasse -c kasse --requests=cpu=15m,memory=100Mi --limits=cpu=100m,memory=128Mi
pluto detect-files -d alt -o wide
pluto detect-files -d alt -t k8s=v1.37.0
pluto detect-files -d alt -t k8s=v1.37.0 --ignore-unavailable-replacements --ignore-removals >/dev/null; echo "exit $?"
pluto detect-helm -o wide
pluto detect-api-resources -o wide
popeye:
  excludes:
    global:
      codes: ["108", "1102", "105"]
    linters:
      pods:
        instances:
          - fqns: [rx:^laden/(netshoot|werkbank)]
            codes: ["208", "1204", "206", "300", "302", "306", "106", "102"]
Code or switch Meaning
💥 / 😱 / 🔊 / ✅ error / warning / info / OK
POP-106 no requests and limits
POP-1100 no Pod matches the Service selector
POP-1109 only one endpoint behind the Service
POP-401 key in the Secret is not used by any Pod
-o json, -o junit, -o html, -o score report for pipelines and archiving, just the number
Pluto exit 2 / 3 / 4 deprecated / removed / deprecated and REPL AVAIL false
VPA MODE Off recommend only; 15m and 100Mi are lower bounds, not a measurement

“0 SCANNED, 100 %” means not checked. Pluto without -t k8s=… compares with an older target version. In kind, the metrics-server needs --kubelet-insecure-tls, in the lab only.

Checking Manifests (Day 10)

kubeconform -summary manifeste/
kubeconform -strict -summary manifeste/neu.yaml
kubeconform -strict -kubernetes-version 1.37.0 -summary manifeste/laden.yaml
kubeconform -strict -summary -schema-location default \
  -schema-location 'https://raw.githubusercontent.com/datreeio/CRDs-catalog/main/{{.Group}}/{{.ResourceKind}}_{{.ResourceAPIVersion}}.json' \
  manifeste/l7.yaml
kube-linter lint manifeste/ > kl.txt 2>&1; echo "exit $?"
grep -o "(check: [a-z-]*" kl.txt | sort | uniq -c | sort -rn
kube-linter checks list --format plain | grep -A2 -E "^Name: (latest-tag|dangling-service)$"
kube-linter lint --config .kube-linter.yaml manifeste/ 2>&1 | tail -1
kube-score score manifeste/kasse.yaml
kube-score score -o ci manifeste/*.yaml | grep "v1/Service"
kube-score score -o ci --ignore-test container-image-pull-policy \
  --ignore-test container-ephemeral-storage-request-and-limit manifeste/*.yaml | grep -c CRITICAL
kube-score list
polaris audit --audit-path manifeste/ --format score
polaris audit --audit-path manifeste/ --format pretty --only-show-failed-tests --severity danger
polaris audit --format pretty | grep -A4 "ClusterRoleBinding api-alles-lesen"
polaris audit --audit-path manifeste/ --set-exit-code-on-danger --format score >/dev/null; echo "exit $?"
checks:
  addAllBuiltIn: false
  exclude:
    - no-anti-affinity
    - no-read-only-root-fs
  include:
    - latest-tag
  annotations:
    ignore-check.kube-linter.io/privileged-container: "begründet in Ticket LAGER-17"
Tool Checks Strength
kubeconform schema fast, version-exact, CRDs via schema catalogs
kube-linter rules clear checks, exceptions via annotation
kube-score rules relationships between objects (Service ↔︎ Pods, PDB, policy)
Polaris rules files and cluster, score, dashboard, admission

Schema first, then rules: kube-linter skips broken files and reports exit 0. Without -strict, unknown fields such as replica: disappear silently. Give kube-score all files together. Polaris without --audit-path checks the current context; --set-exit-code-on-danger exits with 3, --set-exit-code-below-score 80 with 4. An exception always applies to only one check.

Security (Days 11, 15)

grep " trivy_${V}_Linux-$A.tar.gz$" trivy_${V}_checksums.txt | sha256sum -c
trivy image --quiet --severity HIGH,CRITICAL --format json nginx:1.30.7-alpine \
  | jq -r '.Results[].Vulnerabilities[]? | [.PkgName, .VulnerabilityID, .Severity, .InstalledVersion, .FixedVersion] | @tsv'
trivy image --quiet --severity CRITICAL --ignore-unfixed redis:8.2.3-alpine
trivy image --quiet --severity CRITICAL --format json nginxinc/nginx-unprivileged:1.30.6-alpine \
  | jq -r '.Results[] | .Vulnerabilities[]? | [.PkgName, .VulnerabilityID, .InstalledVersion, .FixedVersion] | @tsv'
trivy k8s --include-namespaces laden --report summary --format json --quiet --disable-node-collector > laden-trivy.json
trivy k8s --include-namespaces laden --report all --scanners rbac --quiet --disable-node-collector | grep -A3 "KSV-0111"
sed -i "s#aquasec/kube-bench:latest#aquasec/kube-bench:v0.16.0#" job-master.yaml job.yaml
kubectl apply -f job-master.yaml
kubectl wait --for=condition=complete job/kube-bench-master --timeout=240s
kubectl logs job/kube-bench-master > bench-master.txt
grep "^\[FAIL\]" bench-master.txt
grep -A3 "^1.2.16 " bench-master.txt
kubectl delete job kube-bench kube-bench-master
kubescape scan framework nsa --include-namespaces laden --keep-local 2>/dev/null
kubescape scan framework nsa --include-namespaces laden --keep-local --format json --output ks-nsa.json >/dev/null 2>&1
kubescape scan control C-0035 --keep-local 2>/dev/null | grep -E "Administrative"
rbac-tool lookup -e "kasse|api|betrachter"
rbac-tool who-can get secrets
rbac-tool who-can delete pods
rbac-tool policy-rules -e "kasse" | grep -E "secrets|pods/exec" | head -4
polaris audit --format pretty --only-show-failed-tests --severity danger | grep -A8 "in namespace keller"
kubectl label --dry-run=server --overwrite ns laden lager pod-security.kubernetes.io/enforce=baseline
Layer Question Tool
Image Which known vulnerabilities are in the packages? Trivy (image, k8s)
Workload Is the Pod spec configured dangerously? Trivy, Kubescape (and Day 10)
Node and control plane Are file permissions and parameters set according to CIS? kube-bench
Permissions Who may do what, and by which detour? rbac-tool, Trivy rbac

Most important Trivy column: Fixed Version. Pipeline rule: fail on CRITICAL with a fix (--severity CRITICAL --ignore-unfixed --exit-code 1). Kubescape: “Action Required” (skipped in the JSON report) with 0 resources is not a pass; without --submit, results stay local. Pin kube-bench to a fixed version before applying it; the Jobs mount /etc/kubernetes and /var/lib/etcd.

Helm and GitOps (Days 12, 15)

curl -sL https://github.com/databus23.gpg | gpg --import
gpg --list-keys --with-fingerprint EA17A2A206AFF8CD | head -3
helm plugin install https://github.com/databus23/helm-diff/releases/download/v3.15.15/diff-3.15.15-linux-${ARCH}.tgz
helm diff version
helm get values headlamp -n headlamp
helm get values headlamp -n headlamp --revision 4
helm diff upgrade headlamp headlamp/headlamp -n headlamp --version 0.46.0 --reuse-values --set replicaCount=2 -C 2
helm diff upgrade headlamp headlamp/headlamp -n headlamp --version 0.46.0 --reuse-values --detailed-exitcode >/dev/null 2>&1; echo "exit $?"
helm diff upgrade headlamp headlamp/headlamp -n headlamp --version 0.46.0 -f headlamp-values.yaml | grep -E "^headlamp,"
helm upgrade headlamp headlamp/headlamp -n headlamp --version 0.46.0 -f headlamp-values.yaml | grep REVISION
helm history headlamp -n headlamp --max 2
helm diff revision headlamp 2 3 -n headlamp -C 1
helm rollback headlamp 2 -n headlamp
helm template headlamp headlamp/headlamp --version 0.46.0 --set clusterRoleBinding.create=false | kubeconform -strict -summary -kubernetes-version 1.37.0
helm template headlamp headlamp/headlamp --version 0.46.0 | kube-linter lint --include cluster-admin-role-binding - 2>&1 | grep -E "cluster-admin|Error" | cut -c1-160
kubectl apply -n argocd --server-side -f https://raw.githubusercontent.com/argoproj/argo-cd/v3.6.2/manifests/core-install.yaml
kubectl config set-context --current --namespace=argocd
argocd login --core
argocd app create guestbook --repo https://github.com/argoproj/argocd-example-apps.git --path guestbook \
  --dest-server https://kubernetes.default.svc --dest-namespace guestbook --sync-option CreateNamespace=true
argocd app list
argocd app diff guestbook
argocd app sync guestbook | tail -4
argocd app wait guestbook --health --timeout 180 | tail -3
argocd app get guestbook | grep -E "Sync Status|^apps"
argocd app set guestbook --sync-policy automated --self-heal
argocd app set <app> --sync-policy none
argocd app delete guestbook --yes
kubectl -n argocd wait --for=delete application/guestbook --timeout=120s
flux check --pre
flux install --components=source-controller,kustomize-controller
flux create source git podinfo --url=https://github.com/stefanprodan/podinfo --tag=6.9.2 --interval=10m
flux create kustomization podinfo --source=GitRepository/podinfo --path=./kustomize --prune=true \
  --target-namespace=podinfo --interval=10m --wait=false
flux get kustomizations -A
flux reconcile kustomization podinfo
flux get all -A
flux tree kustomization podinfo
flux diff kustomization podinfo --path ./podinfo/kustomize; echo "exit $?"
flux suspend kustomization podinfo
flux resume kustomization podinfo
flux export source git podinfo
flux uninstall --silent
Diff Question Exit on changes
helm diff upgrade … --detailed-exitcode What does this chart upgrade with these values change? 2
argocd app diff <app> Does the cluster deviate from the state in Git? 1
flux diff kustomization <name> --path <folder> What would change if this folder were merged? 1

helm upgrade --set without --reuse-values forgets all earlier values; better put all values in a file (-f). A rollback is a new revision. Helm 4 installs plugins from a Git repo only with --verify=false; the right way is the release archive with .prov and a verified key. Delete the Argo CD app before uninstalling and wait for the finalizer to finish. Flux --target-namespace does not create the namespace. In an incident: suspend, intervene, put the cause into the repo, resume.

Throwaway Clusters (Day 13)

kind create cluster --config wegwerf.yaml
kind load docker-image laden/lieferung:1.30.6-gepatcht --name wegwerf
kind export logs ./kind-logs --name wegwerf
kind delete cluster --name wegwerf
kind get clusters
k3d cluster create probe --agents 1 -p "8089:80@loadbalancer" --kubeconfig-switch-context=false
k3d cluster list
k3d image import <image> -c probe
k3d cluster delete probe
ctlptl apply -f ctlptl.yaml
ctlptl get cluster
ctlptl get registry
ctlptl delete -f ctlptl.yaml
kubectl --context kind-mitregistry -n kube-public get configmap local-registry-hosting -o jsonpath='{.data}{"\n"}'
docker stats --no-stream --format "{{.Name}} {{.MemUsage}}" | grep -E "k3d|werkzeuge"
kind: Cluster
apiVersion: kind.x-k8s.io/v1alpha4
name: wegwerf
nodes:
- role: control-plane
  extraPortMappings:
  - containerPort: 30080
    hostPort: 8088
- role: worker
apiVersion: ctlptl.dev/v1alpha1
kind: Registry
name: laden-registry
port: 5005
---
apiVersion: ctlptl.dev/v1alpha1
kind: Cluster
product: kind
name: kind-mitregistry
registry: laden-registry
Command Context afterwards
kind create cluster switches to the new cluster
ctlptl apply switches
k3d cluster create … --kubeconfig-switch-context=false stays
kind delete cluster error: current-context is not set, back with kubectl config use-context kind-werkzeuge

With kind, the ctlptl cluster name must start with kind-. k3d brings Traefik, a load balancer and metrics-server; Traefik only arrives after the Helm Job helm-install-traefik.

Your Own Plugins in Go (Day 14)

go mod init example.com/kubectl-ohnelimits
go get k8s.io/[email protected] k8s.io/[email protected] k8s.io/[email protected] k8s.io/[email protected] github.com/spf13/cobra
go mod tidy
go vet ./... && echo vet-ok
gofmt -l .
go build -o kubectl-ohnelimits .
CGO_ENABLED=0 GOOS=linux GOARCH=arm64 go build -ldflags="-s -w" -o /tmp/kubectl-ohnelimits-arm64 .
install -m 755 kubectl-ohnelimits ~/.local/bin/
kubectl ohnelimits -n laden; echo "exit $?"
kubectl ohnelimits --context kubedrill -n default; echo "exit $?"
kubectl ohnelimits -A --as=system:serviceaccount:laden:kasse; echo "exit $?"
kubectl krew install --manifest=ohnelimits.yaml --archive=ohnelimits-v0.1.0-linux-${ARCH}.tar.gz
kubectl krew uninstall ohnelimits
kubectl krew index add firma <url>
    flags := genericclioptions.NewConfigFlags(true)
    config, err := flags.ToRESTConfig()
    ns, _, err := flags.ToRawKubeConfigLoader().Namespace()
    flags.AddFlags(cmd.Flags())
Building block Purpose
client-go talks to the API server, types for all built-in resources
cli-runtime (genericclioptions.ConfigFlags) all of kubectl’s connection flags with the same behavior
Krew manifest download address and SHA-256 per platform; testable locally with --archive
detached/ohnelimits in kubectl krew list from no index, kubectl krew upgrade leaves it alone
Plugin exit codes 0 = everything set, 1 = hits, 2 = error

The Traps from the Book

Trap Day
kind create cluster switches the current context 0, 13
kubectl wait --for=condition=Available returns before all replicas are ready 1
JSON Merge Patch replaces the whole container list 2
view-secret without a key or --all waits forever in scripts 4
Helm charts for UIs often bind cluster-admin (clusterRoleBinding.create) 6
A filter on ERROR misses the cause that comes from the shell 7
Ephemeral containers read the target’s environment, including passwords from Secrets 7
hubble observe --protocol dns stays empty without a CiliumNetworkPolicy with a DNS rule 8
With -n, Popeye reports “0 SCANNED” for some sections 9
Pluto without -t considers removed APIs merely deprecated 9
kube-linter does not read broken files and exits with 0 10
During the file run, Polaris does not know built-in roles (or that does not exist) 10
helm upgrade --set without --reuse-values brings the admin binding back 12, 15
argocd app delete returns immediately; the finalizer needs the controller 12
kind delete cluster leaves no current-context behind 13
Debug containers retroactively violate Pod Security baseline 15

Contents

More