Skip to content
Visual explainer 4h to learn 4 steps

kubectl fluency: imperative commands, dry-run, explain

Generate YAML with --dry-run=client -o yaml and edit it quickly in vim.

By Invicly Tech, , in Kubernetes Administrator (CKA). About 8 minutes to read.

Topic 3 of 33

In short

Speed with kubectl is the biggest time saver on the CKA. Imperative commands create simple objects instantly, and --dry-run=client -o yaml generates a manifest you can edit for anything more complex. kubectl explain shows field names without leaving the terminal.

Explained simply

On the CKA you type a lot of kubectl. Writing YAML from scratch is slow and easy to get wrong, so experts let kubectl write the first draft. Imperative commands like kubectl create deployment build an object in one line, and the dry-run flag turns that line into YAML you can edit.

It is like using a form letter instead of a blank page. You fill in the name and image on the command line, get a correct skeleton, then add the two or three fields the task wants. Less typing means fewer indentation mistakes.

A handful of habits make you fast: a short alias, shell completion, a variable for the dry-run flags, and a vim setup that uses spaces instead of tabs. Together they can save twenty minutes over a whole exam.

Press Play on a diagram to walk through it one step at a time.

FlowGenerate, edit, apply
  1. 1
    Generate YAML

    kubectl create or run with --dry-run=client -o yaml.

  2. 2
    Save to file

    Redirect output to a file like pod.yaml.

  3. 3
    Edit in vim

    Add fields; check names with kubectl explain.

  4. 4
    Apply

    kubectl apply -f pod.yaml.

  5. 5
    Verify

    kubectl get, describe or logs.

MapWhich kubectl verb for which job
kubectl
  • Create
    • run (Pod)
    • create (most kinds)
    • expose (Service)
    • apply -f (from YAML)
  • Change
    • set image/env/resources
    • scale
    • label, annotate
    • edit, replace --force
  • Read
    • get -o wide/yaml/jsonpath
    • describe
    • logs
    • explain
  • Remove
    • delete
    • delete --force --grace-period=0

In depth

The commands that cover most tasks

kubectl run makes a single Pod, and kubectl create makes almost everything else: deployment, service, configmap, secret, serviceaccount, role, rolebinding, clusterrole, job, cronjob, ingress, quota and priorityclass. kubectl expose builds a Service from an existing Deployment or Pod, reusing its labels as the selector.

For changes, kubectl set image, set env and set resources edit a Deployment's template without opening an editor. kubectl scale changes replicas, and kubectl label and annotate add metadata. Each of these is one line, and each one is faster and safer than editing YAML by hand.

  • k run tmp --image=busybox:1.36 --rm -it --restart=Never -- sh
  • k create cronjob c --image=busybox:1.36 --schedule="*/5 * * * *" -- date
  • k set resources deploy web --requests=cpu=100m,memory=64Mi

Dry-run and the edit loop

--dry-run=client asks kubectl to build the object locally without sending it, and -o yaml prints it. Redirect that into a file, open it in vim, add what the command line cannot express (volumes, probes, affinity), then kubectl apply -f.

Many people store the flags in a variable: export do="--dry-run=client -o yaml". Then k create deploy web --image=nginx $do > web.yaml is short and hard to mistype. --dry-run=server is different: it sends the object to the API server for full validation but still does not save it, which is handy for catching admission errors.

CompareClient vs server dry-run
--dry-run=client
  • Object built by kubectl locally
  • Nothing sent to the API server
  • Fast way to generate YAML
--dry-run=server
  • Sent to the API server
  • Full validation and admission checks
  • Still not saved

Changing fields that cannot be edited

Some fields are immutable on a running Pod, such as most of the container spec. kubectl edit then refuses to save and writes your version to a file in /tmp. The fastest fix is kubectl replace --force -f that file, which deletes the old Pod and creates the new one in one step.

To delete Pods fast in drills, add --force --grace-period=0 so kubectl does not wait the default 30 seconds. Use it only on Pods you do not care about, because the app gets no time to shut down cleanly.

FlowFixing an immutable Pod field
  1. Step 1
    kubectl edit pod

    Change a container field

  2. Step 2
    Save is refused

    Field cannot change on a running Pod

  3. Step 3
    Copy kept in /tmp

    kubectl prints the file path

  4. Step 4
    kubectl replace --force -f

    Deletes the old Pod, creates the new one

Getting just the data you need

Tasks often ask you to write information to a file. -o wide adds node and IP columns. -o jsonpath picks fields, for example the image of every Pod. --sort-by sorts by any field, and custom-columns builds a neat table. -l filters by label and --field-selector filters by fields such as status.phase.

kubectl explain is your offline field reference: kubectl explain deploy.spec.strategy describes one field, and adding --recursive prints the whole tree under it.

  • -o jsonpath='{.items[*].spec.containers[*].image}'
  • --sort-by=.metadata.creationTimestamp
  • -o custom-columns=NAME:.metadata.name,NODE:.spec.nodeName

Learn it in 4 short steps

About 1h each. Track them with a timer in your plan.

  1. 1
    Create resources imperatively with kubectl~1h
  2. 2
    Generate YAML with --dry-run=client -o yaml~1h
  3. 3
    Look up fields with kubectl explain~1h
  4. 4
    Set aliases and edit YAML fast in vim~1h

Key points

  • kubectl run creates Pods; kubectl create deployment creates Deployments.
  • kubectl expose creates a Service from an existing Pod or Deployment.
  • kubectl explain pod.spec.containers --recursive lists every nested field.
  • Set vim to two-space indentation with expandtab to avoid YAML tab errors.

Key terms

Tap a card to flip it. 0/5 known

Examples

bash
alias k=kubectl
export do="--dry-run=client -o yaml"

k run web --image=nginx:1.27 --port=80 $do > pod.yaml
k create deployment api --image=httpd --replicas=3 $do > deploy.yaml
k expose deployment api --port=80 --target-port=8080
k create configmap app --from-literal=MODE=prod
k create job once --image=busybox -- echo hi
k explain deployment.spec.strategy

A Pod with a volume in under a minute

Task: create Pod cache with image redis:7 that mounts an emptyDir at /data. Step 1: generate the skeleton with kubectl run and dry-run. Step 2: open it and add volumeMounts under the container and volumes under spec. Step 3: apply and check the mount.

bash
export do="--dry-run=client -o yaml"
k run cache --image=redis:7 $do > cache.yaml
vi cache.yaml
#   containers[0]: volumeMounts: [{name: data, mountPath: /data}]
#   spec:          volumes: [{name: data, emptyDir: {}}]
k apply -f cache.yaml
k exec cache -- df -h /data

Writing sorted data to a file

Task: write the names of all Pods in namespace web, oldest first, to /opt/pods.txt. Step 1: sort by creation time. Step 2: print only names using custom-columns with no header. Step 3: check the file.

bash
k -n web get pods --sort-by=.metadata.creationTimestamp \
  -o custom-columns=NAME:.metadata.name --no-headers > /opt/pods.txt
cat /opt/pods.txt

Quick reference

  • export do="--dry-run=client -o yaml" then k create deploy x --image=nginx $do > x.yaml
  • export now="--force --grace-period=0" for instant Pod deletes in practice
  • k replace --force -f /tmp/kubectl-edit-xxxx.yaml when edit refuses a change
  • k explain pod.spec --recursive | less to browse every field
  • vim: set expandtab tabstop=2 shiftwidth=2 in ~/.vimrc
  • k get pods -A -o wide shows node and IP for every Pod
  • --dry-run=server validates on the API server without saving

Common mistakes

  • Writing YAML from scratch when a generated skeleton takes seconds.
  • Mixing tabs into YAML, which kubectl rejects.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1Which command prints Deployment YAML without creating anything?

Question 2

2kubectl edit refuses to save a change to a running Pod's container. What is the quickest fix?

Question 3

3What creates a ClusterIP Service for an existing Deployment named api on port 80 forwarding to 8080?

Question 4

4What does --dry-run=server add over --dry-run=client?

0/4 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Create a Pod named web with image nginx:1.27 and label tier=front using a single command.

  2. Exercise 2medium

    Generate a CronJob named backup that runs busybox:1.36 with the command "echo done" every 15 minutes, save it to backup.yaml, and add successfulJobsHistoryLimit: 2 before applying.

  3. Exercise 3hard

    Print a table of every Pod in the cluster with columns NAMESPACE, NAME, NODE and the first container's image, sorted by node.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Should I memorise YAML for every resource?
No. Memorise which kubectl command generates each skeleton and where the docs example lives. Then you only add a few fields by hand.
Is the alias k already set up in the exam?
Yes, the exam terminal has the k alias and kubectl completion ready. Practise with the same setup so it feels familiar.
What is the difference between apply and create -f?
create fails if the object already exists. apply creates it or updates it to match the file, so it is safer to rerun.

Go deeper

ShareXLinkedInWhatsApp