Platform Engineering Exercises
The first four exercises are small pieces of the logic inside a portal, a template updater, a cost tool and the Kubernetes admission chain, written as pure Python functions with the calls already in place. Run the starter first: it prints placeholder answers. Complete the code marked TODO until the output matches the expected output, then compare with the solution. The last two are real sessions to fix.
Exercise 1: Orphans and blast radius
Topics: Ownership & the Catalog Graph
orphans returns the entities whose owner is not an existing group (sorted). dependents returns every entity that depends on target directly or transitively (sorted).
GROUPS = {"team-links", "team-growth", "team-platform"}
ENTITIES = {
"component:linkly": {"owner": "team-links", "dependsOn": ["resource:links-db", "resource:cache"]},
"component:redirector": {"owner": "team-links", "dependsOn": ["resource:cache"]},
"component:analytics": {"owner": "team-growth", "dependsOn": ["component:linkly"]},
"component:qr-codes": {"owner": "team-qr", "dependsOn": ["component:redirector"]},
"component:reports": {"owner": "user:ada", "dependsOn": ["component:analytics"]},
"resource:links-db": {"owner": "team-links", "dependsOn": []},
"resource:cache": {"owner": "team-platform", "dependsOn": []},
}
def orphans(entities, groups):
# TODO: entities whose owner is not in groups, sorted
return []
def dependents(entities, target):
# TODO: everything that depends on target, directly or through other entities, sorted
return []
print("orphans:", orphans(ENTITIES, GROUPS))
for t in ["resource:links-db", "resource:cache"]:
deps = dependents(ENTITIES, t)
owners = sorted({ENTITIES[d]["owner"] for d in deps})
print(f"{t} -> {deps}")
print(f" owners to notify: {owners}")orphans: []
resource:links-db -> []
owners to notify: []
resource:cache -> []
owners to notify: []
Expected output:
orphans: ['component:qr-codes', 'component:reports']
resource:links-db -> ['component:analytics', 'component:linkly', 'component:reports']
owners to notify: ['team-growth', 'team-links', 'user:ada']
resource:cache -> ['component:analytics', 'component:linkly', 'component:qr-codes', 'component:redirector', 'component:reports']
owners to notify: ['team-growth', 'team-links', 'team-qr', 'user:ada']Show solution
def orphans(entities, groups):
return sorted(e for e, spec in entities.items() if spec["owner"] not in groups)
def dependents(entities, target):
result, frontier = set(), [target]
while frontier:
cur = frontier.pop()
for e, spec in entities.items():
if cur in spec["dependsOn"] and e not in result:
result.add(e); frontier.append(e)
return sorted(result)reports is both an orphan (owned by a person) and in the blast radius of the database: during an incident, nobody would be notified for it. That combination is what a weekly catalog report should flag first.
Exercise 2: Three-way decisions for a template update
Topics: Keeping Services in Step with the Template
For each file, compare the old template render (BASE), the service today (OURS) and the new template render (THEIRS); a missing key means the file doesn't exist on that side. Return one of: same on both sides (ours equals theirs), take template / added by template / deleted by template (only the template changed it), keep service (only the service changed it), or CONFLICT (both changed it differently).
BASE = {"ci.yaml": "workflow@v3", "values.yaml": "replicas: 2", "README.md": "# svc",
"Makefile": "build", "old.cfg": "x=1"}
OURS = {"ci.yaml": "workflow@v3", "values.yaml": "replicas: 3", "README.md": "# svc (team notes)",
"Makefile": "build", "old.cfg": "x=1", "notes.md": "ours"}
THEIRS = {"ci.yaml": "workflow@v4", "values.yaml": "replicas: 2", "README.md": "# svc + runbook",
"Makefile": "build", "pdb.yaml": "minAvailable: 1"}
def decide(name, base, ours, theirs):
b, o, t = base.get(name), ours.get(name), theirs.get(name)
# TODO
return "?"
for name in sorted(set(BASE) | set(OURS) | set(THEIRS)):
print(f"{name:12} {decide(name, BASE, OURS, THEIRS)}")Makefile ?
README.md ?
ci.yaml ?
notes.md ?
old.cfg ?
pdb.yaml ?
values.yaml ?
Expected output:
Makefile same on both sides
README.md CONFLICT
ci.yaml take template
notes.md keep service
old.cfg deleted by template
pdb.yaml added by template
values.yaml keep serviceShow solution
def decide(name, base, ours, theirs):
b, o, t = base.get(name), ours.get(name), theirs.get(name)
if o == t:
return "same on both sides"
if b == o:
return "deleted by template" if t is None else ("added by template" if b is None else "take template")
if b == t:
return "keep service"
return "CONFLICT"notes.md exists only in the service (b == t == None), so it's the team's file and stays. Order matters: check o == t first, so identical changes on both sides (common when a team back-ported a template fix by hand) are never conflicts.
Exercise 3: Showback vs chargeback
Topics: Cost Allocation by Label
Complete bill. Each team pays its direct cost plus a share of the shared namespaces proportional to its direct cost. With share_idle=False (showback), idle (cluster cost minus everything allocated) is reported as __idle__; with share_idle=True (chargeback) it is split the same way. Round to cents. Both bills must add up to the cluster cost.
CLUSTER_COST = 1000.0
DIRECT = {"team-growth": 300.0, "team-links": 200.0, "team-qr": 100.0} # allocated by max(request, usage)
SHARED = {"monitoring": 90.0, "kube-system": 30.0} # platform namespaces
def bill(direct, shared, cluster_cost, share_idle):
out = {}
# TODO
return out
print("showback (idle separate):", bill(DIRECT, SHARED, CLUSTER_COST, False))
print("chargeback (idle shared):", bill(DIRECT, SHARED, CLUSTER_COST, True))
print("totals:", round(sum(bill(DIRECT, SHARED, CLUSTER_COST, False).values()), 2),
round(sum(bill(DIRECT, SHARED, CLUSTER_COST, True).values()), 2))showback (idle separate): {}
chargeback (idle shared): {}
totals: 0 0
Expected output:
showback (idle separate): {'team-growth': 360.0, 'team-links': 240.0, 'team-qr': 120.0, '__idle__': 280.0}
chargeback (idle shared): {'team-growth': 500.0, 'team-links': 333.33, 'team-qr': 166.67}
totals: 1000.0 1000.0Show solution
def bill(direct, shared, cluster_cost, share_idle):
allocated = sum(direct.values()) + sum(shared.values())
idle = cluster_cost - allocated
total_direct = sum(direct.values())
out = {}
for team, cost in direct.items():
w = cost / total_direct
out[team] = cost + sum(shared.values()) * w + (idle * w if share_idle else 0)
if not share_idle:
out["__idle__"] = idle
return {k: round(v, 2) for k, v in out.items()}The chargeback bill makes team-growth pay 500 for 300 of direct use. Whether that's fair is a policy question, which is why idle is usually kept separate until teams trust the model.
Exercise 4: Does the Pod fit the tenant's quota?
Topics: A Tenant Namespace Kit, Multi-Tenancy Models
Model admission in a tenant namespace. For each container, a missing request defaults to the container's limit if it has one, otherwise to DEFAULT_REQUEST (the LimitRange). Reject a container whose memory limit (or, without one, its memory request) is above MAX_MEMORY. Then reject the Pod if USED plus its total requests exceeds the quota. Check each Pod on its own against USED.
QUOTA = {"requests.cpu": 2000, "requests.memory": 4096} # millicores, MiB
USED = {"requests.cpu": 1500, "requests.memory": 3000}
DEFAULT_REQUEST = {"cpu": 100, "memory": 128} # from the LimitRange
MAX_MEMORY = 2048 # LimitRange max per container (limit)
def admit(pod):
# TODO: apply defaults, check MAX_MEMORY per container, then the quota
return "?"
pods = [
{"name": "web", "containers": [{"name": "app", "requests": {"cpu": 250, "memory": 256}}]},
{"name": "no-requests", "containers": [{"name": "app"}, {"name": "sidecar"}]},
{"name": "big", "containers": [{"name": "app", "requests": {"cpu": 600}}]},
{"name": "hungry", "containers": [{"name": "app", "limits": {"memory": 3072}}]},
]
for p in pods:
print(f"{p['name']:12} {admit(p)}")web ?
no-requests ?
big ?
hungry ?
Expected output:
web admitted (cpu 250m, memory 256Mi)
no-requests admitted (cpu 200m, memory 256Mi)
big rejected: exceeded quota requests.cpu: used 1500 + requested 600 > 2000
hungry rejected: container app memory limit 3072Mi > max 2048MiShow solution
def admit(pod):
total = {"requests.cpu": 0, "requests.memory": 0}
for c in pod["containers"]:
limits = c.get("limits", {})
req = {k: c.get("requests", {}).get(k, limits.get(k, DEFAULT_REQUEST[k])) for k in DEFAULT_REQUEST}
limit_mem = limits.get("memory", req["memory"])
if limit_mem > MAX_MEMORY:
return f"rejected: container {c['name']} memory limit {limit_mem}Mi > max {MAX_MEMORY}Mi"
total["requests.cpu"] += req["cpu"]
total["requests.memory"] += req["memory"]
for k, v in total.items():
if USED[k] + v > QUOTA[k]:
return f"rejected: exceeded quota {k}: used {USED[k]} + requested {v} > {QUOTA[k]}"
return f"admitted (cpu {total['requests.cpu']}m, memory {total['requests.memory']}Mi)"no-requests is admitted only because the LimitRange filled in requests: without them, a namespace with a quota on requests.cpu rejects Pods that don't declare requests at all. The real API server also applies default limits and checks min/ratios; the model keeps the two rules that surprise teams most.
Exercise 5: The tenant kit that kubeconform rejects
Topics: A Tenant Namespace Kit, kubeconform
A new team's namespace objects were written by hand, and the validation step fails. Fix only the YAML so all three objects are valid.
cat > tenant.yaml <<'EOF'
apiVersion: v1
kind: ResourceQuota
metadata: {name: tenant-quota, namespace: team-qr}
spec:
hardLimits:
requests.cpu: "4"
pods: "40"
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata: {name: tenant-developers, namespace: team-qr}
roleRef: {kind: ClusterRole, name: edit}
subjects:
- {apiGroup: rbac.authorization.k8s.io, kind: Group, name: qr-devs}
---
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata: {name: default-deny, namespace: team-qr}
spec:
podSelector: {}
policyTypes: [Ingress, Egress]
egress:
- to: [{namespaceSelector: {matchLabels: {kubernetes.io/metadata.name: kube-system}}}]
ports: [{protocol: UDP, port: 53}]
port: 53
EOF
kubeconform -n 1 -strict -summary tenant.yaml 2>&1 | sed -E 's/ - at /\n at /g; s/problem validating schema.*json#.//'tenant.yaml - ResourceQuota tenant-quota is invalid:
at '/spec': additional properties 'hardLimits' not allowed
tenant.yaml - RoleBinding tenant-developers is invalid:
at '/roleRef': missing property 'apiGroup'
tenant.yaml - NetworkPolicy default-deny is invalid:
at '/spec/egress/0': additional properties 'port' not allowed
Summary: 3 resources found in 1 file - Valid: 0, Invalid: 3, Errors: 0, Skipped: 0
Expected output:
Summary: 3 resources found in 1 file - Valid: 3, Invalid: 0, Errors: 0, Skipped: 0Show solution
spec:
hard: # the field is `hard`
requests.cpu: "4"
pods: "40"
---
roleRef: {apiGroup: rbac.authorization.k8s.io, kind: ClusterRole, name: edit} # apiGroup is required
---
egress:
- to: [{namespaceSelector: {matchLabels: {kubernetes.io/metadata.name: kube-system}}}]
ports: [{protocol: UDP, port: 53}, {protocol: TCP, port: 53}] # no stray `port:` keyWithout -strict, hardLimits and the stray port would have passed validation. Whether the API server then rejects them or silently drops them depends on the client's field validation setting (kubectl defaults to strict; other tools may not), and a silent drop means a namespace with no quota and a DNS rule that only looks right. Add TCP 53 while you're there: DNS falls back to TCP for large responses.
Exercise 6: Placeholders that survive rendering
Topics: Rendering a Golden Path
The golden path's CI renders the skeleton with sample answers and fails when any ${{ … }} placeholder is left. Two survive. Fix only the skeleton files (not render.sh) so the session prints no placeholders left.
mkdir -p skeleton
cat > skeleton/catalog-info.yaml <<'EOF'
apiVersion: backstage.io/v1alpha1
kind: Component
metadata:
name: ${{ values.name }}
spec:
type: service
owner: ${{ values.ownr }}
lifecycle: experimental
EOF
cat > skeleton/values.yaml <<'EOF'
image: ghcr.io/acme/${{values.name}}
replicaCount: 2
EOF
cat > render.sh <<'EOF'
#!/bin/bash
set -euo pipefail
yq -o=props "$2" | sed -E 's/^([^ ]+) = (.*)$/s|\\$\\{\\{ values.\1 \\}\\}|\2|g/' > render.sed
for f in $(cd "$1" && find . -type f | sort); do
mkdir -p "$(dirname "$3/$f")" && sed -E -f render.sed "$1/$f" > "$3/$f"
done
EOF
chmod +x render.sh
printf 'name: shortlinks\nowner: team-growth\n' > answers.yaml
./render.sh skeleton answers.yaml out
if grep -rq '\${{' out; then grep -rn '\${{' out | sort; else echo "no placeholders left"; fiout/catalog-info.yaml:7: owner: ${{ values.ownr }}
out/values.yaml:1:image: ghcr.io/acme/${{values.name}}
Expected output:
no placeholders leftShow solution
# skeleton/catalog-info.yaml
owner: ${{ values.owner }} # was values.ownr: no such answer
# skeleton/values.yaml
image: ghcr.io/acme/${{ values.name }} # the renderer expects one space inside the bracesBoth mistakes render "successfully" and would ship a broken catalog entry and an image name with a literal placeholder. That's why the template's CI renders with sample answers and greps the result, and why real template engines are configured to fail on undefined values where they can.
Test yourself
In a three-way template update, the service and the new template made the same change to a file. What should happen?
- Conflict
- Nothing to do: both sides agree
- Take the old version
- Delete the file
Why did hardLimits in a ResourceQuota only fail with -strict?
- It is a valid field
- Without -strict, unknown fields are allowed by the schema; depending on the client, the API server might then drop them silently, leaving no quota
- kubeconform has no ResourceQuota schema
- Quotas are optional