root access

$ cat ckad-prep/part-01.md

CKAD Prep, Part 1: Building Pods the YAML Way

CKAD Prep, Part 1: Building Pods the YAML Way — namespace setup, command vs args, and jsonpath: spec vs status

Why I’m writing this

Hi, I’m Reza. I usually share my projects from the beginning. This series is a little different: it’s my preparation for the CKAD exam (Certified Kubernetes Application Developer). I am a junior engineer looking for my first SRE, DevOps or Cloud job, and that is why I learn in public. You can see how I think, what breaks, and how I fix it.

I practice on my own home lab: a K3s cluster on a machine called thor. I work through a set of lab scenarios, and for each one I write notes: the code line by line, the mistakes I made, and the real output.

YAML by hand is slow, and the exam is timed. So the workflow uses both styles:

Imperative to start, declarative to keep: generate a skeleton with kubectl run --dry-run=client, edit the YAML, apply it with kubectl apply -f, then verify with jsonpath, events and logs

In this part I set up the lab, then do the first three pod scenarios: a pod with everything set (A1), command vs args (A2), and pulling facts out of a pod (A3).

Setup: a namespace and a default context

Every lab starts the same way: a namespace for the lab, and a default context that points at it.

apiVersion: v1
kind: Namespace
metadata:
  name: core
  • apiVersion: v1 is the core API group. Namespaces, Pods, Services, ConfigMaps and Secrets all live in the same v1 group.
  • kind: Namespace is case-sensitive. namespace in lowercase gets rejected. One of the lab’s later scenarios hits the same rule with a Pod.
  • name: core must be a valid DNS label: lowercase letters, digits and -, up to 63 characters. That’s because the name ends up in the API path, and the path has to stay valid.
  • There is no metadata.namespace. A Namespace is cluster-scoped, so it doesn’t live inside another namespace.
  • There is no spec. A Namespace needs nothing beyond its name.

Then three commands:

sudo mkdir -p /opt/ckad/00/yaml && sudo chown -R $USER /opt/ckad
kubectl apply -f /opt/ckad/00/yaml/00-namespace.yaml
kubectl config set-context --current --namespace=core
  • /opt belongs to root, so sudo creates the folder, and chown gives it to me. Without the chown, every later command would need sudo, and the exam doesn’t work that way.
  • apply is declarative: “make the cluster match this file”. It creates the object if it’s missing, and patches it if it exists. A second apply changes nothing, and prints unchanged.
  • config set-context edits my local kubeconfig file (~/.kube/config). It doesn’t talk to the cluster at all, so it works even if the cluster is down.

The part that’s easy to misunderstand: set-context --namespace only changes the default for my commands. It doesn’t move anything. And it doesn’t override a namespace: written inside a YAML file.

Without this step, everything goes to default, and you need -n core on every command. Forgetting -n is the kind of mistake that costs points in a timed exam.

kubectl config view --minify | grep namespace
namespace: core

--minify prints only the current context, so grep finds that context’s namespace and nothing else. A full kubectl config view prints every context and cluster, and the grep would match the wrong lines.

One design note: on the exam, kubectl create ns core is faster for something this small. I use YAML here so the namespace sits in the repo with the rest of the lab, and so every lab file in the same folder applies the same way.

A1: a pod with everything set

The task: a pod called web, with labels, an env var, a container port, and CPU and memory requests and limits. The pod runs nginx, and I check it with jsonpath.

The skeleton

kubectl run web --image=nginx:1.27 \
  --labels=app=web,tier=frontend \
  --env=MODE=prod \
  --port=80 --dry-run=client -o yaml > yaml/a1-web-pod.yaml
  • kubectl run only makes pods. Not Deployments: --replicas was removed years ago.
  • nginx:1.27 is a pinned tag. In a lab I’ll repeat, I never use latest. If the image changes, the results change, and the notes stop matching.
  • --labels is comma-separated, with no spaces. These labels matter later: kubectl expose pod web copies them onto the Service selector, and a Service with no matching labels finds no pods.
  • --port=80 sets containerPort: 80. On its own, it doesn’t open anything. It’s information that Services and probes can use.
  • --dry-run=client builds the object locally and never sends it to the API server. Without it, the pod would be created right away, and I’d have nothing to edit.

What kubectl run cant do: resources

kubectl run can’t set resources anymore, so that part is always written by hand:

resources:
  requests:
    cpu: 100m
    memory: 64Mi
  limits:
    cpu: 200m
    memory: 128Mi
  • resources sits under the container, not under spec. Each container has its own. At pod level it fails validation.
  • 100m is 100 millicores, so 0.1 of a CPU core.
  • 64Mi is 64 mebibytes (1024-based). 64M is megabytes (1000-based), a different number. I use Mi and Gi, never M and G.
  • Requests are what the scheduler reserves. The pod only goes on a node with 100m CPU and 64Mi still free.
  • Limits are the ceiling. Above 200m CPU, the container is throttled (slowed down, not killed). Above 128Mi memory, it is killed with OOMKilled.
  • If you set limits without requests, Kubernetes copies the limits into the requests.

A few other details in the file:

  • No metadata.namespace, so the pod goes to my default namespace, core. The file stays reusable, but it only works if the context points at core.
  • The container is named web, because kubectl run names it after the pod. Later commands like kubectl logs web use the pod name, not the container name.
  • Env values must be strings. value: 8080 without quotes is read as a number and rejected. Write "8080".
  • I removed the dry-run noise: creationTimestamp: null, resources: {} and status: {}. It’s harmless, but it hides the real content when you’re reading the file.

QoS class

Kubernetes gives every pod a Quality of Service class, worked out from its requests and limits:

  • Guaranteed: every container has requests equal to limits, for both CPU and memory.
  • Burstable: at least one request or limit is set, but it isn’t Guaranteed. web is this one, because its requests are below its limits.
  • BestEffort: nothing set. These pods are evicted first when a node runs out of memory.

Problem: jsonpath printed two blank lines

To check the QoS class, I ran:

kubectl get pods -o jsonpath='{.spec.containers[0].resources}{"\n"}{.status.qosClass}{"\n"}'

It printed two empty lines. No error, just nothing.

The cause: kubectl get pods, with no name, returns a List. Its top level is {"kind":"List","items":[...]}, so .spec and .status don’t exist there. jsonpath doesn’t error on a missing path. It prints nothing.

kubectl get pod web -o jsonpath='{.spec.containers[0].resources}{"\n"}{.status.qosClass}{"\n"}'

Or, to list them, go through items:

kubectl get pods -o jsonpath='{range .items[*]}{.metadata.name}{"\t"}{.status.qosClass}{"\n"}{end}'

The rule I’m keeping: one object, start with .spec. A list, start with .items[*].

Result

NAME   READY   STATUS    RESTARTS   AGE   LABELS
web    1/1     Running   0          35s   app=web,tier=frontend

prod comes from kubectl exec web -- printenv MODE. Labels, env, port and resources: all four are the same in the file and on the running pod.

A2: command vs args

This one confuses a lot of people, so here is the short version first:

  • command replaces the image’s ENTRYPOINT (the program).
  • args replaces the image’s CMD (the arguments to that program).

The task: two busybox pods. sleeper sets only command. printer sets command and args, and its logs give a line to save.

The skeletons, and what — means

kubectl run sleeper --image=busybox:1.36 --command --dry-run=client -o yaml -- sleep 3600
kubectl run printer --image=busybox:1.36 --dry-run=client -o yaml -- sh -c "echo hello; sleep 3600"
  • -- ends kubectl’s own flags. Everything after it goes into the container. Without --, kubectl would try to read sleep as its own flag, and fail.
  • With --command, what comes after -- becomes the command.
  • Without --command, it becomes args. That works with busybox, because busybox has no ENTRYPOINT, so the first arg becomes the program to run.
  • The quotes keep "echo hello; sleep 3600" as one argument. Without them, my own shell would split it into words before kubectl ever saw it.

sleeper

apiVersion: v1
kind: Pod
metadata:
  name: sleeper
spec:
  containers:
  - name: sleeper
    image: busybox:1.36
    command: ["sleep", "3600"]
  • One list item per argument. "3600" is quoted, because every item must be a string. The number 3600 gets rejected.
  • command: ["sleep 3600"] as one string would look for a program literally called sleep 3600, and fail with executable file not found.
  • Why a command at all? busybox’s default is CMD ["sh"]. Without a terminal, sh exits straight away, and the pod goes into CrashLoopBackOff. sleep 3600 keeps the container alive for an hour. That’s the standard trick for a debug pod.

printer

---
apiVersion: v1
kind: Pod
metadata:
  name: printer
spec:
  containers:
  - name: printer
    image: busybox:1.36
    command: ["sh", "-c"]
    args: ["echo hello; sleep 3600"]
  • --- separates YAML documents. Both pods are in one file, because they belong to the same scenario. One apply creates both.
  • sh -c runs the next argument as a script. The args item is that script, as one string.
  • A shell is needed because ; is shell syntax. Without sh -c, command: ["echo", "hello;", "sleep", "3600"] would just print hello; sleep 3600 and exit.
  • The final argv is command + args, joined. command: ["sh", "-c", "echo hello; sleep 3600"] does exactly the same thing. I split it only to show both fields side by side.

The four combinations

  1. Neither set: the image’s ENTRYPOINT + the image’s CMD.
  2. Only args: the image’s ENTRYPOINT + your args.
  3. Only command: your command, and the image’s CMD is ignored.
  4. Both: your command + your args.

busybox has an empty ENTRYPOINT and CMD ["sh"], which is why cases 2 and 3 both work here. Try nginx, and case 3 runs the command with no arguments at all, because nginx’s CMD is a set of flags, not a shell.

Saving the logs, and a wrong path

kubectl wait --for=condition=Ready pod/printer --timeout=60s
kubectl logs printer > /opt/ckad/00/printer.txt

kubectl wait blocks until the pod is Ready. Without it, kubectl logs right after apply can hit a container that hasn’t started yet.

My first try was kubectl logs printer > printer.txt. That wrote to my home folder, but the lab checks /opt/ckad/00/printer.txt. On the exam, a correct answer in the wrong path scores zero. I fixed it with mv.

I also had a typo in a jsonpath check: a stray " printed ["sleep","3600"]". jsonpath prints any text outside {} as it is. Harmless here, but in an answer file it would make the answer wrong.

Result

NAME      READY   STATUS    RESTARTS   AGE
sleeper   1/1     Running   0          3m43s
printer   1/1     Running   0          93s

A3: pull facts out of a pod

The task: write web‘s IP, node name and image to /opt/ckad/00/web-info.txt, one per line. One jsonpath call writes all three lines.

kubectl get pod web -o jsonpath='{.status.podIP}{"\n"}{.spec.nodeName}{"\n"}{.spec.containers[0].image}{"\n"}' > /opt/ckad/00/web-info.txt
  • get pod web names one object, so the jsonpath root is the Pod itself. That’s the A1 lesson again.
  • Single quotes stop bash from touching {, }, " and $ inside the expression.
  • {"\n"} is a literal newline. Without it, the output would be 10.42.1.33thornginx:1.27, all on one line.
  • > overwrites the file. >> would append, so a second run would duplicate the lines.

Where each value lives: spec vs status

This is the part I want to remember. Two values are in spec, and one is in status:

  • .status.podIP: the CNI (Flannel, on K3s) hands out the IP when the pod starts. It’s something the cluster assigns, not something I set.
  • .spec.nodeName: the scheduler writes this when it binds the pod to a node. It’s an assignment, not a request.
  • .spec.containers[0].image: the image you asked for. The image actually running, with its digest, is .status.containerStatuses[0].imageID.

Every Kubernetes object works like this. spec is the desired state, written by you or a controller. status is the observed state, written back by the cluster.

Finding a field path

Two ways, with no memorizing:

  • kubectl get pod web -o yaml: read the indentation, then join the keys with ..
  • kubectl explain pod.status.podIP: shows the field’s documentation, and proves the path exists.

Preview first, then redirect

I ran the command once without >, checked the three lines, then ran it again with > file. It costs a second, and it saves a wrong file.

And why jsonpath instead of copying from kubectl get pods -o wide by hand? Typing values by hand risks a typo in an IP, and the checker compares exact strings.

Result

10.42.1.33
thor
nginx:1.27

It matches the IP and NODE columns of kubectl get pods -o wide. All three pods are on 10.42.1.x, because K3s puts all the pods on the same node network.

What I learned

  • Skeleton first, then edit. kubectl run --dry-run=client -o yaml gives correct YAML indentation in seconds.
  • set-context --namespace only changes the default. It moves nothing, and a namespace: in a file still wins.
  • One object, .spec. A list, .items[*]. jsonpath doesn’t fail on a wrong path. It prints nothing.
  • command is ENTRYPOINT, args is CMD. After -- in kubectl run, it’s args, unless you add --command.
  • Every list item in command and args is a string, and one string is one argument.
  • spec is what you asked for. status is what the cluster saw.
  • Check the path of every answer file. A right answer in the wrong place scores zero.
  • Preview a query before you redirect it to a file.

What is next

In Part 2, I break things on purpose. I change an image on a running pod (that works) and a CPU limit (that fails). I also learn why some fields are immutable, and how to recover when I change the wrong one.

$ ls -t root-access/ | head -3

Building a Job Board API, Part 32: The Fresh Machine Found Two Bugs job-board-api · 32/32 13 min Building a Job Board API, Part 31: Installed Is Not the Same as Working job-board-api · 31/32 10 min Building a Job Board API, Part 30: Deprecated Tools and a Versioned Role job-board-api · 30/32 14 min

Leave a comment

Your email address will not be published. Required fields are marked *