Skip to Content
Asterrr's Handbook

kubectl skills

The kubectl habits that save minutes per task. Imperative generators, dry-run, explain, output formats with jsonpath and custom columns, label, patch and set, apply versus create versus replace, diff, wait, copy and port-forward.

Exam tasks: all of them. This page covers no single competency, because every task is typed through kubectl.

The decision: which command creates, changes or reads the object with the fewest keystrokes and the least chance of a YAML mistake?

yesno, new objectyesnoyesnoTask: create or change anobjectGenerator exists?Flags enough?Run thegeneratorDry-run YAML,edit, applyCopy from docsor explainChanging an existingobject?set, label,patch, edit
Pick the creation path. Use an imperative generator when kubectl can build the object, generate YAML with a dry run when you must add fields, and write YAML by hand only when nothing else fits.
--dry-run=client -o yaml
Print the object without sending it. The base of every generated manifest.
kubectl explain
Field documentation from the cluster's own API, including the CRDs installed.
-A
Every namespace. --all-namespaces is the long form.
--as
Impersonate a user or ServiceAccount to test RBAC.
--field-selector, -l
Filter by fields such as status.phase or by labels.

Imperative generators

CreateCommand
Podk run web --image=nginx:1.27 --port=80 --labels=a=b --env=K=V
Deploymentk create deploy web --image=nginx:1.27 --replicas=3 --port=80
Service from a workloadk expose deploy web --port=80 --target-port=8080 --type=NodePort --name=web-svc
Job, CronJobk create job j --image=busybox:1.36 -- date and k create cronjob c --image=busybox:1.36 --schedule="*/5 * * * *" -- date
ConfigMap, Secretk create cm app --from-literal=K=V --from-file=app.conf and k create secret generic db --from-literal=pw=x
ServiceAccount, Namespacek create sa ci -n ops and k create ns ops
Role, RoleBindingk create role r --verb=get,list --resource=pods and k create rolebinding rb --role=r --user=jana
ClusterRole, ClusterRoleBindingk create clusterrole cr --verb=get --resource=nodes and k create clusterrolebinding crb --clusterrole=cr --user=jana
Ingressk create ingress web --class=nginx --rule="shop.test/cart*=cart:80"
Quota, PriorityClassk create quota q --hard=pods=10,cpu=4 and k create pc high --value=1000
export do="--dry-run=client -o yaml"
k create deploy web --image=nginx:1.27 --replicas=3 $do > web.yaml     # edit, then: k apply -f web.yaml
k run tmp --rm -it --image=busybox:1.36 --restart=Never -- wget -qO- http://web.shop    # throwaway test Pod
  • k run creates a Pod. For anything with replicas, use k create deploy.
  • Generators cannot set everything. k create deploy has no --env, --resources or probe flags in the form you need: generate, edit and apply. k set env, k set resources and k set image change an existing workload.
  • No generator exists for NetworkPolicy, PersistentVolume, PersistentVolumeClaim, StorageClass, HPA with custom metrics or Gateway API objects. Copy a manifest from the docs and edit it.

kubectl explain

k explain pod.spec.containers.securityContext          # one level
k explain deploy.spec.strategy.rollingUpdate           # field types and descriptions
k explain pod.spec --recursive | less                  # the whole tree, search with /
k explain backups.spec --api-version=vault.lab.io/v1   # a custom resource
k api-resources --namespaced=false                     # cluster-scoped kinds
k api-resources | grep -i polic                        # short names and API groups

explain works offline from the cluster's OpenAPI schema, so it is faster than the browser and always matches the cluster's version.

Reading output

GoalCommand
More columns-o wide
Labels--show-labels or -L app,tier
One field-o jsonpath='{.items[*].metadata.name}'
Loop over items-o jsonpath='{range .items[*]}{.metadata.name}{"\t"}{.status.podIP}{"\n"}{end}'
Chosen columns-o custom-columns=NAME:.metadata.name,IMAGE:.spec.containers[0].image,NODE:.spec.nodeName
Sorted--sort-by=.metadata.creationTimestamp or --sort-by=.status.capacity.storage
Filter by label-l app=web,tier!=db
Filter by field--field-selector status.phase=Running,spec.nodeName=worker-1
The saved YAML-o yaml
Watch-w
k get nodes -o jsonpath='{range .items[*]}{.metadata.name}{"\t"}{.status.nodeInfo.kubeletVersion}{"\n"}{end}'
k get pods -A --field-selector status.phase!=Running
k get pv --sort-by=.spec.capacity.storage
k get events -A --sort-by=.lastTimestamp | tail -20

Exam signal

Tasks that say "write the names of … to a file" are checking your output flags. Write exactly what was asked, one per line, and cat the file to check it before you move on.

Changing a live object

NeedCommand
Image, env or resources of a workloadk set image deploy/web web=nginx:1.28 and k set env deploy/web K=V and k set resources deploy/web --limits=cpu=500m,memory=256Mi
Replicask scale deploy/web --replicas=5
Labels and annotationsk label pod web tier=front --overwrite and k annotate pod web note="canary" and a trailing - removes one (k label pod web tier-)
Node maintenancek cordon n1, k drain n1 --ignore-daemonsets --delete-emptydir-data, k uncordon n1
Taintsk taint nodes n1 gpu=true:NoSchedule and k taint nodes n1 gpu=true:NoSchedule- to remove
A single fieldk patch deploy web -p '{"spec":{"replicas":4}}'
A list itemk patch pod web --type=json -p '[{"op":"replace","path":"/spec/containers/0/image","value":"nginx:1.28"}]'
In an editork edit deploy web
  • patch defaults to a strategic merge patch. --type=merge replaces lists whole, and --type=json addresses one item by path.
  • k edit on a field that cannot change fails and saves the file under /tmp. Fix the file and run k replace --force -f <file>.

apply, create, replace, diff

CommandCreatesUpdatesNeeds the object to exist
create -fYesNo, errors with AlreadyExistsNo
apply -fYesYes, three-way merge, stores last-applied-configurationNo
replace -fNoYes, whole object, requires resourceVersion match when setYes
replace --force -fYesDelete, then createNo
apply --server-sideYesYes, field ownership tracked by the serverNo
  • k diff -f file.yaml shows what apply would change.
  • k apply -f dir/ applies every manifest in a directory. Add -R for subdirectories, and -k dir/ for Kustomize.
  • Mixing create and apply on one object makes apply warn about a missing annotation. Use one habit per object.

Waiting, copying, forwarding

k wait --for=condition=Ready pod/web --timeout=60s
k wait --for=condition=Available deploy/web --timeout=120s
k wait --for=delete pod/old --timeout=60s
k rollout status deploy/web
k cp shop/web-0:/var/log/app.log ./app.log -c web     # needs tar in the container
k port-forward svc/web 8080:80 &                       # then curl localhost:8080
k exec -it web-0 -c web -- sh
k auth can-i create deploy --as=jana -n shop
k debug node/worker-1 -it --image=busybox:1.36         # a Pod on the node with the host file system at /host

Namespaces and cleanup

  • k get ns, k create ns x, k delete ns x removes everything inside. A namespace stuck in Terminating usually has an unavailable APIService or a finalizer on something inside.
  • k config set-context --current --namespace=x changes the default. Reset it to default after the task if your habits need it.
  • Fast delete in the exam: k delete pod web --force --grace-period=0. Use $now as defined on the exam page.

Scenarios

Scenario
A task says: 'Create a Deployment api with 3 replicas of nginx:1.27 that sets the environment variable MODE=prod and requests 100m CPU.' Which approach is the fastest correct one?
Scenario
A task says: 'Write the names of all Pods in all namespaces that are not Running to /tmp/notrunning.txt, one name per line.' Which command produces the correct file?
Scenario
An engineer runs 'kubectl edit pod web' to change the Pod's memory limit and the editor refuses with a field is immutable error. The Pod is not owned by a controller. What is the quickest correct way to apply the change?

Drill

kubectl config use-context cka-lab1

Write to /tmp/nodes.txt the name and kubelet version of each node, tab-separated. Write the names of all Pods in the kube-system namespace sorted by creation time, oldest first, to /tmp/pods.txt. Then create a Pod probe in default that runs sleep 1d, labeled role=probe and env=lab, and remove the env label from it.

Further reading

On this page