Skip to content
Hands-on IT IT Drills

Day 1: Exam Craft

Goal: You create, change and read Kubernetes objects so fast that the clock is not your opponent in the exam. · Duration: approx. 60 min · Prerequisite: Day 0

Briefing

The CKAD has roughly 15 to 20 tasks in 120 minutes, each with its own weight. You work in a terminal; many tasks start with an ssh to a specific host and a context or namespace switch. Today you train the moves that every following day takes for granted:

  • Alias k, completion, $do and $now
  • Set up vim for YAML
  • Generate YAML instead of typing it, find fields with k explain
  • Filter output: -o yaml, jsonpath, custom-columns, --sort-by

Drill 1: Alias, completion, shortcuts

On cp1, into ~/.bashrc:

cat <<'EOF' >> ~/.bashrc
source <(kubectl completion bash)
alias k=kubectl
complete -o default -F __start_kubectl k
export do="--dry-run=client -o yaml"
export now="--force --grace-period=0"
EOF
source ~/.bashrc
type k
echo $do
echo $now

Expected:

k is aliased to `kubectl'
--dry-run=client -o yaml
--force --grace-period=0

$do generates YAML without creating anything. $now deletes immediately instead of waiting for the 30-second grace period. Test the completion: k get po -n kube-<TAB>.

Save your progress? Sign up for free

Drill 2: vim for YAML

YAML does not tolerate tabs. Three lines in ~/.vimrc are enough:

cat <<'EOF' > ~/.vimrc
set expandtab
set tabstop=2
set shiftwidth=2
EOF
cat ~/.vimrc

Expected:

set expandtab
set tabstop=2
set shiftwidth=2

Useful in vim: :set paste before pasting from the docs, V plus > or < indents or outdents the selected lines by two spaces, u undoes.

Save your progress? Sign up for free

Drill 3: Hosts, contexts, namespaces

In the exam you work via ssh on changing hosts. kubectl is not set up everywhere – try it on a worker (from your own machine):

ssh [email protected] kubectl get nodes

Expected (shortened):

The connection to the server localhost:8080 was refused - did you specify the right
host or port?

Without a kubeconfig, kubectl asks localhost:8080. This message almost always means: wrong host. Back on cp1:

k config get-contexts
k create ns tag01
k config set-context --current --namespace=tag01
k config view --minify -o jsonpath='{..namespace}{"\n"}'

Expected:

CURRENT   NAME                          CLUSTER      AUTHINFO           NAMESPACE
*         kubernetes-admin@kubernetes   kubernetes   kubernetes-admin   default
namespace/tag01 created
Context "kubernetes-admin@kubernetes" modified.
tag01

From now on, everything without -n lands in tag01.

Save your progress? Sign up for free

Drill 4: Create imperatively

mkdir -p ~/ckad/tag01 && cd ~/ckad/tag01
k run web --image=nginx:1.29 --port=80 --labels=app=web,tier=front $do

Expected:

apiVersion: v1
kind: Pod
metadata:
  labels:
    app: web
    tier: front
  name: web
spec:
  containers:
  - image: nginx:1.29
    name: web
    ports:
    - containerPort: 80
    resources: {}
  dnsPolicy: ClusterFirst
  restartPolicy: Always
status: {}

Everything after -- becomes the command; with --command it replaces the entrypoint:

k run tmp --image=busybox:1.37 --restart=Never $do --command -- sleep 3600

Expected (excerpt):

  containers:
  - command:
    - sleep
    - "3600"
    image: busybox:1.37
    name: tmp

The exam way: write to a file, edit, apply. Plus a few objects that every exam needs:

k create deployment api --image=nginx:1.29 --replicas=2 $do > api.yaml
k apply -f api.yaml
k run web --image=nginx:1.29 --port=80 --labels=app=web,tier=front
k expose deployment api --port=80 --target-port=80
k create configmap app-cfg --from-literal=MODE=dev
k create secret generic app-sec --from-literal=PASSWORD=lab-pass
k create job once --image=busybox:1.37 -- date
k create cronjob tick --image=busybox:1.37 --schedule="*/5 * * * *" -- date
k get all

Expected (shortened):

NAME                       READY   STATUS      RESTARTS   AGE
pod/api-5f8476ddb6-hpt8z   1/1     Running     0          38s
pod/api-5f8476ddb6-mz5fj   1/1     Running     0          38s
pod/once-t89gv             0/1     Completed   0          36s
pod/web                    1/1     Running     0          37s

NAME          TYPE        CLUSTER-IP     EXTERNAL-IP   PORT(S)   AGE
service/api   ClusterIP   10.101.243.0   <none>        80/TCP    37s
...
NAME                 SCHEDULE      TIMEZONE   SUSPEND   ACTIVE   LAST SCHEDULE   AGE
cronjob.batch/tick   */5 * * * *   <none>     False     0        <none>          36s

k get all does not show ConfigMaps and Secrets – you query those separately.

Save your progress? Sign up for free

Drill 5: Find fields with explain

The docs are allowed in the exam, but k explain is faster:

k explain cronjob.spec.concurrencyPolicy | head -9

Expected:

GROUP:      batch
KIND:       CronJob
VERSION:    v1

FIELD: concurrencyPolicy <string>
ENUM:
    Allow
    Forbid
    Replace

All fields of a subtree at a glance:

k explain pod.spec.containers.securityContext --recursive | sed -n '/FIELDS/,$p' \
  | head -8

Expected:

FIELDS:
  allowPrivilegeEscalation  <boolean>
  appArmorProfile   <AppArmorProfile>
    localhostProfile    <string>
    type    <string> -required-
    enum: Localhost, RuntimeDefault, Unconfined
  capabilities  <Capabilities>
    add <[]string>

k api-resources shows the short names of resources (cj, deploy, netpol …).

Save your progress? Sign up for free

Drill 6: Filter output

k get pod web -o jsonpath='{.spec.nodeName}{" "}{.status.podIP}{"\n"}'
J='{range .items[*]}{.metadata.name}{"\t"}{.status.phase}{"\n"}{end}'
k get pods -o jsonpath="$J"

Expected:

worker2 192.168.189.78
api-5f8476ddb6-hpt8z    Running
api-5f8476ddb6-mz5fj    Running
once-t89gv  Succeeded
web Running

Custom columns, sorted by age:

C=NAME:.metadata.name,IMAGE:.spec.containers[0].image,NODE:.spec.nodeName
k get pods --sort-by=.metadata.creationTimestamp -o custom-columns=$C

Expected:

NAME                   IMAGE          NODE
api-5f8476ddb6-hpt8z   nginx:1.29     worker2
api-5f8476ddb6-mz5fj   nginx:1.29     worker1
web                    nginx:1.29     worker2
once-t89gv             busybox:1.37   worker1

Filter by label and read a Secret value:

k get pods -l app=api -o name
k get secret app-sec -o jsonpath='{.data.PASSWORD}' | base64 -d; echo

Expected:

pod/api-5f8476ddb6-hpt8z
pod/api-5f8476ddb6-mz5fj
lab-pass

Tip: Tasks like “write the result to /opt/…” you handle with > and then check with cat.

Save your progress? Sign up for free

Drill 7: Change and recreate

Labels, image and replicas can be changed imperatively:

k label pod web env=lab
k set image deployment/api nginx=nginx:1.29-alpine
k rollout status deployment/api
k scale deployment api --replicas=3

Expected (shortened):

pod/web labeled
deployment.apps/api image updated
deployment "api" successfully rolled out
deployment.apps/api scaled

For pods, most fields are immutable. Give web an environment variable – via the same file you could have created it with:

k run web --image=nginx:1.29 --port=80 --labels=app=web,tier=front $do > web.yaml
vim web.yaml

Insert below - image: nginx:1.29:

    env:
    - name: MODE
      value: dev
k apply -f web.yaml

Expected (shortened):

The Pod "web" is invalid: spec: Forbidden: pod updates may not change fields other than
`spec.containers[*].image`,`spec.initContainers[*].image`,`spec.activeDeadlineSeconds`,
...

Delete and recreate in one step:

k replace -f web.yaml $now
k get pod web -o jsonpath='{.spec.containers[0].env}{"\n"}'

Expected:

pod "web" deleted from tag01 namespace
pod/web replaced
[{"name":"MODE","value":"dev"}]

Save your progress? Sign up for free

Drill 8: Test with throwaway pods

A pod that runs once, prints its output and deletes itself:

k run t --rm -i --image=busybox:1.37 --restart=Never -- wget -qO- -T 5 http://api \
  | grep title

Expected:

<title>Welcome to nginx!</title>

The notice lines from k run -i go to stderr and also appear in the terminal.

Events in chronological order, newest at the bottom:

k get events --sort-by=.lastTimestamp | tail -3

Expected (shortened):

1s    Normal   Scheduled   pod/api-f6c848cc4-n6hh9    Successfully assigned tag01/...
1s    Normal   Killing     pod/api-5f8476ddb6-mz5fj   Stopping container nginx
0s    Normal   Killing     pod/web                    Stopping container web

Save your progress? Sign up for free

Exercise: Speed Drills

  1. Create a Deployment shop with nginx:1.29, 2 replicas and container port 80 via a file shop.yaml. Target time: 40 s
  2. Write the name and node of all pods in kube-system without a header line to ks.txt. Target time: 45 s
  3. Find out how many times a Job is retried by default. Target time: 20 s
  4. Delete the pod web without waiting. Target time: 10 s

Solution

k create deployment shop --image=nginx:1.29 --replicas=2 --port=80 $do > shop.yaml
k apply -f shop.yaml
k get pods -n kube-system --no-headers \
  -o custom-columns=:.metadata.name,:.spec.nodeName > ks.txt
k explain job.spec.backoffLimit | grep -A2 DESCRIPTION
k delete pod web $now

Expected (shortened):

deployment.apps/shop created
DESCRIPTION:
    Specifies the number of retries before marking this job failed. Defaults to
    6, unless backoffLimitPerIndex (only Indexed Job) is specified. When
pod "web" force deleted from tag01 namespace

Save your progress? Sign up for free

Checkpoint

type k

Expected: k is aliased to `kubectl'

echo $do

Expected: --dry-run=client -o yaml

k config view --minify -o jsonpath='{..namespace}{"\n"}'

Expected: tag01

k get deployment shop -o jsonpath='{..containerPort}{"\n"}'

Expected: 80

Challenge

Write all container images running in the cluster, without duplicates and sorted, to ~/ckad/tag01/images.txt.

Hint: jsonpath with [*] on two levels returns all images on one line.

Solution

k get pods -A -o jsonpath='{.items[*].spec.containers[*].image}' \
  | tr ' ' '\n' | sort -u > ~/ckad/tag01/images.txt
head -3 ~/ckad/tag01/images.txt

Expected (shortened, depends on your cluster):

busybox:1.37
docker.io/library/registry:3.1.2
docker.io/rancher/local-path-provisioner:v0.0.37

Clean up and reset the namespace:

k config set-context --current --namespace=default
k delete ns tag01

Save your progress? Sign up for free

Exam Tip

  • Every task: first run the given ssh and context command, and exit at the end. If you work in the wrong cluster or namespace, you get zero points.
  • Time: tasks with a high weight and little typing first. If you are stuck for more than five minutes, flag the task and move on.
  • k explain and -h (e.g. k create cronjob -h) show examples – often faster than kubernetes.io.

Enterprise Note

  • In day-to-day work, manifests come from Git (GitOps), not from k create – but $do is the fastest way to a correct skeleton.
  • Several clusters in the kubeconfig: show the current context in the prompt so that nobody accidentally works in production.
  • --force --grace-period=0 is off-limits in production: the container may keep running on the node.