root access

$ cat ckad-prep/part-05.md

CKAD Prep, Part 5: The Selector That Matched 13 Pods

CKAD Prep, Part 5: The Selector That Matched 13 Pods

Where we are

Hi, I’m Reza. I’m sharing my preparation for the CKAD exam, practiced on a K3s cluster in my home lab. I am a junior engineer looking for my first SRE, DevOps or Cloud job, and these posts are my lab notes — what I tried, what worked, and where I went wrong.

In Parts 3 and 4, labels decided everything: which pods a ReplicaSet owns, and which ReplicaSets a Deployment makes. Part 5 is the third level of the same idea: labels and selectors themselves. Three things to do:

  • D1: work in another namespace without switching to it, and count every pod in the cluster.
  • D2: query pods with every kind of selector, and change labels on running pods.
  • D3: annotations, which look like labels but can’t be selected on.

The most important result is in D2. I asked for pods where env is not dev. The precise answer is 2 pods. The query returned 13:

The selector env!=dev matched 13 pods; adding the existence check env,env!=dev narrows it to p1 and p2, and counting all pods gives 79.

A pod with no env label at all also has an env that “isn’t dev”. More on that below.

D1: working across namespaces

The task: create a namespace finance with a pod ledger (redis:7) in it, without switching my default namespace away from core. Then list some pods across all namespaces, and count every pod in the cluster.

One file, two documents

apiVersion: v1
kind: Namespace
metadata:
  name: finance
---
apiVersion: v1
kind: Pod
metadata:
  name: ledger
  namespace: finance
  labels:
    app: ledger
spec:
  containers:
    - name: ledger
      image: redis:7
  • Order matters. apply handles documents from top to bottom, so the namespace must exist before the pod that lives in it. A file with the pod first fails.
  • namespace: finance puts the pod in finance, even though my context says core. That’s how you work in another namespace without switching to it.
  • If the file and the flag disagree, kubectl refuses. With -n core on the command line, you get the namespace and the flag don’t agree.
  • app: ledger isn’t required by the task. I add a label to every workload, so it can always be selected later.
  • redis:7 runs redis-server by default, a long-running process, so it needs no command (unlike busybox, which needs sleep 3600).

The apply said namespace/finance unchanged. That’s not an error: the namespace already existed, and I ran the file twice — once to test it, once for real. Unchanged means the object was already as described.

The priority, from strongest to weakest: metadata.namespace in the file, then the -n flag, then the namespace in the context. If the file says finance, the flag can’t move the pod.

The pod exists, but I can’t see it

kubectl get pods -n finance
kubectl config view --minify | grep namespace

A plain get pods looks in core, so it doesn’t show ledger. That’s the lab’s number one time-waster for me: the object exists, I’m just looking in the wrong namespace. -n finance is the fix, and config view --minify shows the namespace my context defaults to.

Listing across namespaces

kubectl get pods -A -l 'app in (web,api)'
  • -A is --all-namespaces. It adds a NAMESPACE column.
  • app in (web,api) is a set-based selector: app is web or api.
  • The quotes are needed. Without them, bash reads ( as shell syntax and fails.
  • -l app=web,app=api would match nothing. In a label selector, a comma always means AND, and app can’t be both web and api.

The result: 5 api-* pods and web, all in core. ledger (app=ledger) is correctly left out.

Counting every pod: 79

kubectl get pods -A --no-headers | wc -l > /opt/ckad/00/count.txt

The answer was 79. Why so many? kube-system (CoreDNS, Traefik, metrics-server, local-path-provisioner) is the biggest group, then the long list of default, completed and failed pods from earlier tasks. My own live pods are a small part of it.

“All pods” really means all of them, in any phase: Running, Completed, Error, Pending. Counting only Running pods is a different question:

kubectl get pods -A --field-selector=status.phase=Running --no-headers | wc -l

So read the task carefully. And remember --no-headers, or the count is 80.

One more thing: namespaces don’t isolate network traffic. Pods in finance and core can still talk to each other. NetworkPolicies do that, and they select pods by labels — which is where this part of the lab is heading.

D2: selectors, and the != trap

The task: three pods with env and tier labels, a set of queries, then change labels on the running pods. Three pods, one namespace (core):

The starting labels:

  • p1: env=prod, tier=fe
  • p2: env=prod, tier=be
  • p3: env=dev, tier=fe

All three are nginx pods, in one file with three documents. Only the labels differ. env and tier are the example keys for every query below, and the trap is about what happens to a pod that doesn’t have the key at all.

The queries

kubectl get pods -l env=prod

Equality. env is exactly prod: p1 and p2.

kubectl get pods -l env=prod,tier=fe

A comma means AND. Both must be true: only p1. There’s no OR in equality syntax. For OR on one key, use in (below).

kubectl get pods -l 'env!=dev'

Inequality. This returned p1, p2, and 11 more: the 5 api-* pods, the 2 shop-* pods, broken, printer, sleeper and web. None of them have env at all, but “isn’t dev” is true for a missing key. That is the trap: != also matches pods that don’t have the key.

The quotes are needed, because ! means something in bash (history expansion).

kubectl get pods -l 'env,env!=dev'

env on its own is an existence check: the key is there, with any value. ANDed with env!=dev, it gives exactly p1 and p2. That is the precise answer to the task: env is not dev, among pods that have env.

env notin (dev) has the same problem as !=. Only adding the existence check fixes it.

kubectl get pods -l 'tier in (fe,be)'

Set-based in: tier is fe or be. That’s p1, p2 and p3. web has tier=frontend, and values are compared exactly, so web doesn’t match.

All the forms, and which ones match a missing key

  • env=prod: env is prod. Pods with no env: not matched.
  • env!=dev: env isn’t dev. Pods with no env: matched.
  • env in (prod,staging): env is one of these. Pods with no env: not matched.
  • env notin (dev): env isn’t one of these. Pods with no env: matched.
  • env: env exists. Pods with no env: not matched.
  • !env: env doesn’t exist. Only pods with no env.
  • a=1,b=2: both are true (AND).

This trap matters most in places where matching a pod by accident has real effects: NetworkPolicies, Services and controllers all select by labels. A selector that matches pods you didn’t mean to include is a real bug, not just a wrong count.

Changing labels on running pods

kubectl label pod p3 env=staging --overwrite
kubectl label pod p2 tier-
  • Labels can change on a running pod. No restart, and no Forbidden like the CPU limit in Part 2.
  • --overwrite is required, because env already has a value. Without it: error: 'env' already has a value.
  • key-, with a trailing dash, removes the label. Output: pod/p2 unlabeled. The same syntax works for annotations.

And remember Part 3: changing a pod’s labels can move it into or out of a controller’s set. A pod’s labels are what its owner matches on. The lab’s pods are bare, so nothing broke here, but a ReplicaSet’s pods would be a different story.

Syncing the file

Then I edited the file to match (p3 is now staging, p2 has no tier line) and applied it:

  • p1 unchanged.
  • p2 configured, p3 configured. The live labels already matched the file. But apply keeps its own record of what it last applied, and the file now says something different from that record. So it writes the change. That’s the kubectl.kubernetes.io/last-applied-configuration annotation at work, and D3 explains it.

Why is deleting tier from the file enough? apply removes a field that was in its last-applied record and is now missing from the file. That’s how declarative config prunes fields. It only removes fields it manages. A field set by hand (kubectl label) isn’t in the record, so apply won’t remove it.

NAME   READY   STATUS    RESTARTS   AGE   LABELS
p1     1/1     Running   0          14m   env=prod,tier=fe
p2     1/1     Running   0          15m   env=prod
p3     1/1     Running   0          15m   env=staging,tier=fe

A side note: printer and sleeper from Part 1 now show RESTARTS 47. Their sleep 3600 ends every hour, Kubernetes restarts them, and the count keeps climbing. That’s expected for a pod that keeps finishing.

D3: annotations

The task: add the annotations owner=reza and ticket=CKAD-42 to Deployment api, then write ticket‘s value to /opt/ckad/00/ticket.txt. The tricky part is where the annotation goes: on the Deployment itself, not on its pods.

Where the annotation goes matters

metadata:
  name: api
  labels:
    app: api
    team: core
  annotations:
    owner: reza
    ticket: CKAD-42
  • annotations sits next to labels, under the Deployment’s own metadata. Not under spec.template.metadata.labels, which would put it on every pod.
  • So the pod template doesn’t change. No new template hash, no new ReplicaSet, no restart. I checked: the ReplicaSet is still api-7579bcc6c4, from Part 4.
  • Under the template, it would be different. Every pod would get the annotation, the hash would change, and a new ReplicaSet would roll out — for a change that has nothing to do with the pods.
  • Values are strings. CKAD-42 is fine as it is. A value like 42 or true would need quotes, the same rule as labels in Part 3.

I edited the file and applied it (configured), so the repo matches the cluster with no sync step. On this one I made the change in the file first, then applied it — the right order. kubectl annotate would also have worked, but then the file wouldn’t match.

Reading the annotation

kubectl get deployments.apps api -o jsonpath='{.metadata.annotations.ticket}{"\n"}' > /opt/ckad/00/ticket.txt
  • deployments.apps is the full name, <resource>.<group>. Same object as deploy. Tab completion tends to offer the plural form, which is why the command looks like that.
  • annotations is a map, and ticket is a key in it. Result: CKAD-42.

A key with dots in it

Kubernetes writes its own annotations too, and their keys have dots. To read the Deployment’s revision, the key is deployment.kubernetes.io/revision, and dots in a jsonpath key need escaping:

kubectl get deployments.apps api -o jsonpath='{.metadata.annotations.deployment\.kubernetes\.io/revision}{"\n"}'

The key is literally deployment.kubernetes.io/revision. Without the \., jsonpath reads it as annotations → deployment → kubernetes → io/revision, a nested path that doesn’t exist. The result is a silent blank, not an error — the same failure mode as the wrong field name in Part 4.

Revision 4, not 5

The result was 4. I had predicted it might be 5, because of the ReplicaSet I deleted and rebuilt in Part 4. But a revision counts template changes, not ReplicaSets. Deleting and rebuilding the same template, with the same hash, doesn’t make a new revision. And the annotation on the Deployment’s own metadata didn’t change the template either.

Annotations:            deployment.kubernetes.io/revision: 4
                        owner: reza

Labels vs annotations

  • Purpose: labels identify and select. Annotations attach information.
  • Selectable: labels yes (with -l, Services, ReplicaSets). Annotations no.
  • Size: label values are short (63 characters at most, limited characters). Annotations can hold any text, including long values.
  • Who reads them: labels are read by controllers and Services. Annotations are read by tools: kubectl, deployers, dashboards.

Three annotations Kubernetes writes that keep showing up:

  • deployment.kubernetes.io/revision: the Deployment’s current revision, and each ReplicaSet’s own number is in its annotation too.
  • kubectl.kubernetes.io/last-applied-configuration: what apply compares against. That’s what made p2 and p3 configured in the sync step.
  • kubernetes.io/change-cause: fills the CHANGE-CAUSE column in kubectl rollout history.

What I learned

  • metadata.namespace in the file beats the -n flag, which beats the context. If the file and the flag disagree, apply refuses.
  • Put a namespace before the objects that live in it, in the same file.
  • “All pods” means every phase, in every namespace. Running-only is a different question, and --no-headers changes the count by one.
  • A comma in a selector means AND. For OR on one key, use in.
  • != and notin also match pods that don’t have the key. Add an existence check: env,env!=dev.
  • Quote selectors that contain ! or (.
  • Labels change live, with --overwrite for an existing key and key- to remove one. Then sync the file.
  • Annotations can’t be selected on. On the Deployment’s metadata they change nothing. On the template, they roll out new pods.
  • Escape dots in jsonpath keys: deployment\.kubernetes\.io/revision. Otherwise it’s another silent blank.
  • A revision is a template version. Rebuilding the same template doesn’t add one.

What is next

Next in the lab: Services. A stable name and IP in front of pods that keep changing, a broken Service that selects the wrong pods, and the labels that decide who gets the traffic.

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

CKAD Prep, Part 4: Who Owns This Pod? ckad-prep · 4/5 13 min CKAD Prep, Part 3: A ReplicaSet Only Counts ckad-prep · 3/5 10 min CKAD Prep, Part 2: Breaking Pods on Purpose ckad-prep · 2/5 11 min

Leave a comment

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