TExcelTAD
Home › Kubernetes › Kubernetes Exercises

Kubernetes Exercises

Time to practise! Each exercise asks you to implement one of the rules Kubernetes uses to make decisions, in plain Python. Every starter playground runs as-is and prints a placeholder result so you can see the format. Replace the TODO parts, press ▶ Run, and compare with the "Expected" lines. The solutions are hidden below each exercise; try for a few minutes first.

# Exercise Lesson
1 Label selector matching Labels & selectors
2 Service endpoints Services
3 Rolling-update budget Rolling updates
4 QoS class Requests, limits & QoS
5 HPA desired replicas Autoscaling
6 Taints and tolerations Scheduling
7 RBAC check RBAC
8 Manifest linter Objects & manifests

1. Label selector matching

Write matches(labels, selector) for a selector with matchLabels (every pair must be present and equal) and matchExpressions with the operators In, NotIn, Exists and DoesNotExist. Remember that NotIn also matches when the key is missing.

Expected: ['api-1', 'api-3']

python · try it yourself
pods = {
    "api-1": {"app": "api", "env": "prod"},
    "api-2": {"app": "api", "env": "dev"},
    "api-3": {"app": "api", "env": "staging", "canary": "true"},
    "web-1": {"app": "web", "env": "prod"},
}
selector = {
    "matchLabels": {"app": "api"},
    "matchExpressions": [{"key": "env", "operator": "NotIn", "values": ["dev"]}],
}

def matches(labels, selector):
    # TODO: check matchLabels, then each expression
    return False

print([name for name, labels in pods.items() if matches(labels, selector)])
[]
Show solution
python
def matches(labels, selector):
    for key, value in selector.get("matchLabels", {}).items():
        if labels.get(key) != value:
            return False
    for e in selector.get("matchExpressions", []):
        key, op, values = e["key"], e["operator"], e.get("values", [])
        if op == "In" and labels.get(key) not in values:
            return False
        if op == "NotIn" and key in labels and labels[key] in values:
            return False
        if op == "Exists" and key not in labels:
            return False
        if op == "DoesNotExist" and key in labels:
            return False
    return True

2. Service endpoints

A Service routes only to Pods that match its selector and are Ready, on its targetPort. Write endpoints(service, pods) returning a list of "ip:port" strings in Pod order.

Expected: ['10.244.1.4:8080', '10.244.3.2:8080']

python · try it yourself
service = {"selector": {"app": "api"}, "port": 80, "targetPort": 8080}
pods = [
    {"ip": "10.244.1.4", "labels": {"app": "api"}, "ready": True},
    {"ip": "10.244.2.6", "labels": {"app": "api"}, "ready": False},
    {"ip": "10.244.2.9", "labels": {"app": "web"}, "ready": True},
    {"ip": "10.244.3.2", "labels": {"app": "api", "track": "canary"}, "ready": True},
]

def endpoints(service, pods):
    # TODO
    return []

print(endpoints(service, pods))
[]
Show solution
python
def endpoints(service, pods):
    result = []
    for p in pods:
        selected = all(p["labels"].get(k) == v for k, v in service["selector"].items())
        if selected and p["ready"]:
            result.append(f"{p['ip']}:{service['targetPort']}")
    return result

3. Rolling-update budget

Write budget(replicas, max_surge, max_unavailable) that accepts numbers or percentage strings and returns (max_pods, min_available). Percentages are taken of replicas; maxSurge rounds up, maxUnavailable rounds down.

Expected: (13, 8) for budget(10, "25%", "25%") and (6, 4) for budget(5, 1, "20%").

python · try it yourself
import math

def budget(replicas, max_surge, max_unavailable):
    # TODO: convert both values, then compute the two bounds
    return (replicas, replicas)

print(budget(10, "25%", "25%"))
print(budget(5, 1, "20%"))
(10, 10)
(5, 5)
Show solution
python
import math

def resolve(value, replicas, round_up):
    if isinstance(value, str) and value.endswith("%"):
        exact = int(value[:-1]) * replicas / 100
        return math.ceil(exact) if round_up else math.floor(exact)
    return value

def budget(replicas, max_surge, max_unavailable):
    surge = resolve(max_surge, replicas, round_up=True)
    unavailable = resolve(max_unavailable, replicas, round_up=False)
    return (replicas + surge, replicas - unavailable)

4. QoS class

Write qos(containers) returning "Guaranteed", "Burstable" or "BestEffort". A missing request defaults to the limit. Guaranteed needs CPU and memory limits on every container with requests equal to limits.

Expected: BestEffort, Guaranteed, Burstable, Burstable

python · try it yourself
cases = [
    [{}],
    [{"limits": {"cpu": "1", "memory": "1Gi"}}],
    [{"requests": {"cpu": "1", "memory": "1Gi"}, "limits": {"cpu": "2", "memory": "1Gi"}}],
    [{"limits": {"cpu": "1", "memory": "1Gi"}}, {"requests": {"memory": "64Mi"}}],
]

def qos(containers):
    # TODO
    return "?"

for c in cases:
    print(qos(c))
?
?
?
?
Show solution
python
def qos(containers):
    if all(not c.get("requests") and not c.get("limits") for c in containers):
        return "BestEffort"
    for c in containers:
        req, lim = c.get("requests", {}), c.get("limits", {})
        for res in ("cpu", "memory"):
            if res not in lim or req.get(res, lim[res]) != lim[res]:
                return "Burstable"
    return "Guaranteed"

5. HPA desired replicas

Implement the HPA rule: ceil(current × metric / target), unchanged if the ratio is within 10 % of 1.0, clamped to [min_r, max_r].

Expected: 8, 4, 2, 10

python · try it yourself
import math

def desired(current, metric, target, min_r=2, max_r=10):
    # TODO
    return current

print(desired(4, 100, 50))   # double the load
print(desired(4, 52, 50))    # within tolerance
print(desired(4, 10, 50))    # very quiet
print(desired(6, 400, 50))   # huge spike
4
4
4
6
Show solution
python
import math

def desired(current, metric, target, min_r=2, max_r=10):
    ratio = metric / target
    if abs(ratio - 1) <= 0.1:
        return current
    return max(min_r, min(max_r, math.ceil(current * ratio)))

6. Taints and tolerations

A Pod may be scheduled on a node only if it tolerates every NoSchedule taint on it. A toleration matches a taint when the keys and effects are equal and either operator is Exists or the values are equal. Print the nodes the Pod may use.

Expected: ['node-1', 'node-3']

python · try it yourself
nodes = {
    "node-1": [],
    "node-2": [{"key": "gpu", "value": "true", "effect": "NoSchedule"}],
    "node-3": [{"key": "team", "value": "data", "effect": "NoSchedule"}],
    "node-4": [{"key": "team", "value": "web", "effect": "NoSchedule"}],
}
tolerations = [{"key": "team", "operator": "Equal", "value": "data", "effect": "NoSchedule"}]

def tolerates(taint, tolerations):
    # TODO
    return False

def allowed_nodes(nodes, tolerations):
    return [n for n, taints in nodes.items() if all(tolerates(t, tolerations) for t in taints)]

print(allowed_nodes(nodes, tolerations))
['node-1']
Show solution
python
def tolerates(taint, tolerations):
    for t in tolerations:
        if t["key"] != taint["key"] or t.get("effect") != taint["effect"]:
            continue
        if t.get("operator") == "Exists" or t.get("value") == taint["value"]:
            return True
    return False

7. RBAC check

Write can(rules, verb, resource) for a Role's rules: allowed if any rule lists the verb (or *) and the resource (or *). Then report which of the requested actions the ci ServiceAccount can do.

Expected:

text
get deployments: yes
patch deployments: yes
delete deployments: no
get secrets: no
list pods: yes
python · try it yourself
rules = [
    {"resources": ["deployments"], "verbs": ["get", "list", "patch"]},
    {"resources": ["pods", "pods/log"], "verbs": ["get", "list", "watch"]},
]
requests = [("get", "deployments"), ("patch", "deployments"), ("delete", "deployments"),
            ("get", "secrets"), ("list", "pods")]

def can(rules, verb, resource):
    # TODO
    return False

for verb, resource in requests:
    print(f"{verb} {resource}: {'yes' if can(rules, verb, resource) else 'no'}")
get deployments: no
patch deployments: no
delete deployments: no
get secrets: no
list pods: no
Show solution
python
def can(rules, verb, resource):
    return any((verb in r["verbs"] or "*" in r["verbs"]) and
               (resource in r["resources"] or "*" in r["resources"]) for r in rules)

8. Manifest linter

Parse a multi-document YAML string and report, for every Deployment, each container that (a) uses the :latest tag or no tag, or (b) has no memory limit. Print ok for a clean Deployment.

Expected:

text
web: container nginx uses :latest or no tag
web: container nginx has no memory limit
api: ok
worker: container worker has no memory limit
python · try it yourself
import yaml

manifests = """
apiVersion: apps/v1
kind: Deployment
metadata: {name: web}
spec:
  template:
    spec:
      containers:
        - {name: nginx, image: nginx}
---
apiVersion: v1
kind: Service
metadata: {name: web}
---
apiVersion: apps/v1
kind: Deployment
metadata: {name: api}
spec:
  template:
    spec:
      containers:
        - name: api
          image: ghcr.io/acme/api:2.4.0
          resources: {limits: {memory: 512Mi}}
---
apiVersion: apps/v1
kind: Deployment
metadata: {name: worker}
spec:
  template:
    spec:
      containers:
        - name: worker
          image: ghcr.io/acme/worker:1.9.2
          resources: {requests: {cpu: 200m}}
"""

for doc in yaml.safe_load_all(manifests):
    if doc["kind"] != "Deployment":
        continue
    problems = []
    # TODO: inspect doc["spec"]["template"]["spec"]["containers"]
    name = doc["metadata"]["name"]
    print(f"{name}: ok" if not problems else "\n".join(f"{name}: {p}" for p in problems))
web: ok
api: ok
worker: ok
Show solution
python
for doc in yaml.safe_load_all(manifests):
    if doc["kind"] != "Deployment":
        continue
    problems = []
    for c in doc["spec"]["template"]["spec"]["containers"]:
        image = c["image"]
        last = image.rsplit("/", 1)[-1]
        if ":" not in last or last.endswith(":latest"):
            problems.append(f"container {c['name']} uses :latest or no tag")
        if "memory" not in c.get("resources", {}).get("limits", {}):
            problems.append(f"container {c['name']} has no memory limit")
    name = doc["metadata"]["name"]
    print(f"{name}: ok" if not problems else "\n".join(f"{name}: {p}" for p in problems))

Test yourself

Exercise 3: what is budget(4, "25%", "25%")?

  1. (5, 3)
  2. (5, 4)
  3. (4, 3)
  4. (6, 2)

Exercise 6: a toleration has operator: Exists and key team, effect NoSchedule. Which nodes become allowed?

  1. Only node-3
  2. node-1, node-3 and node-4
  3. All four
  4. Only node-1

Exercise 5: 3 replicas, metric 80, target 50 (min 2, max 10). What is the result?

  1. 3
  2. 4
  3. 5
  4. 6