$ cat ckad-prep/part-05.md
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:

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.
applyhandles 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: financeputs the pod infinance, even though my context sayscore. That’s how you work in another namespace without switching to it.- If the file and the flag disagree,
kubectlrefuses. With-n coreon the command line, you get the namespace and the flag don’t agree. app: ledgerisn’t required by the task. I add a label to every workload, so it can always be selected later.redis:7runsredis-serverby default, a long-running process, so it needs no command (unlikebusybox, which needssleep 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)'
-Ais--all-namespaces. It adds aNAMESPACEcolumn.app in (web,api)is a set-based selector:appisweborapi.- The quotes are needed. Without them, bash reads
(as shell syntax and fails. -l app=web,app=apiwould match nothing. In a label selector, a comma always means AND, andappcan’t be bothwebandapi.
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=fep2:env=prod,tier=bep3: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:envisprod. Pods with noenv: not matched.env!=dev:envisn’tdev. Pods with noenv: matched.env in (prod,staging):envis one of these. Pods with noenv: not matched.env notin (dev):envisn’t one of these. Pods with noenv: matched.env:envexists. Pods with noenv: not matched.!env:envdoesn’t exist. Only pods with noenv.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
Forbiddenlike the CPU limit in Part 2. --overwriteis required, becauseenvalready 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:
p1unchanged.p2configured,p3configured. The live labels already matched the file. Butapplykeeps 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 thekubectl.kubernetes.io/last-applied-configurationannotation 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
annotationssits next tolabels, under the Deployment’s ownmetadata. Not underspec.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-42is fine as it is. A value like42ortruewould 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.appsis the full name,<resource>.<group>. Same object asdeploy. Tab completion tends to offer the plural form, which is why the command looks like that.annotationsis a map, andticketis 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: whatapplycompares against. That’s what madep2andp3configured in the sync step.kubernetes.io/change-cause: fills theCHANGE-CAUSEcolumn inkubectl rollout history.
What I learned
metadata.namespacein the file beats the-nflag, which beats the context. If the file and the flag disagree,applyrefuses.- 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-headerschanges the count by one. - A comma in a selector means AND. For OR on one key, use
in. !=andnotinalso match pods that don’t have the key. Add an existence check:env,env!=dev.- Quote selectors that contain
!or(. - Labels change live, with
--overwritefor an existing key andkey-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
jsonpathkeys: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.