Show contents
Chapter 6 of 7 · 25 min
Project: deploying an API and checking its manifests
By the end of this chapter, you'll be able to
- Assemble an application's complete manifests: Deployment, Service, ConfigMap and autoscaler
- Link objects together by their names and labels
- Write a checker that applies production rules to manifests
- Test the checker on a good and a bad manifest
The application's manifests
A single file can hold several objects, separated by ---. Here are the essentials:
apiVersion: v1
kind: ConfigMap
metadata:
name: harvest-config
data:
WEIGHT_UNIT: "kg"
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: harvest-api
labels: {app: harvest-api}
spec:
replicas: 2
selector:
matchLabels: {app: harvest-api}
template:
metadata:
labels: {app: harvest-api}
spec:
containers:
- name: api
image: registry.example.com/harvest-api:2.1.0
ports: [{containerPort: 8000}]
envFrom: [{configMapRef: {name: harvest-config}}]
readinessProbe: {httpGet: {path: /ready, port: 8000}}
livenessProbe: {httpGet: {path: /alive, port: 8000}}
resources:
requests: {cpu: 250m, memory: 256Mi}
limits: {memory: 256Mi}
---
apiVersion: v1
kind: Service
metadata:
name: harvest-api
spec:
selector: {app: harvest-api}
ports: [{port: 80, targetPort: 8000}]
---
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: harvest-api
spec:
scaleTargetRef: {apiVersion: apps/v1, kind: Deployment, name: harvest-api}
minReplicas: 2
maxReplicas: 6
metrics:
- type: Resource
resource: {name: cpu, target: {type: Utilization, averageUtilization: 70}}
Objects are linked by names (the harvest-config ConfigMap, the autoscaler's target) and by labels (app: harvest-api, chosen by the Service). A single typo, and one object no longer finds the other.
The autoscaler adjusts the number of replicas of the Deployment it names.
Text description of the animation
- The configuration lives in its own ConfigMap.
- The Deployment injects it into each container, referring to it by name.
- The pods created carry the template's label.
- The Service finds the pods by this label and sends them traffic.
- The autoscaler adjusts the number of replicas of the Deployment it names.
The checker
The team's rules: at least 2 replicas, an image with a precise version, readiness and liveness probes, CPU and memory requests, and a Service that really selects a Deployment's pods. In practice, you would read the YAML file with a library (yaml.safe_load_all); here, the manifests are already Python dictionaries.
def check(objects):
problems = []
deployments = [o for o in objects if o["kind"] == "Deployment"]
for d in deployments:
name = d["metadata"]["name"]
spec = d["spec"]
if spec.get("replicas", 1) < 2:
problems.append(f"{name}: fewer than 2 replicas")
for c in spec["template"]["spec"]["containers"]:
image = c["image"]
if ":" not in image or image.endswith(":latest"):
problems.append(f"{name}: image without a precise version ({image})")
for probe in ("readinessProbe", "livenessProbe"):
if probe not in c:
problems.append(f"{name}: {probe} missing")
requests = c.get("resources", {}).get("requests", {})
for r in ("cpu", "memory"):
if r not in requests:
problems.append(f"{name}: requests.{r} missing")
for s in (o for o in objects if o["kind"] == "Service"):
selector = s["spec"]["selector"]
found = any(
all(d["spec"]["template"]["metadata"]["labels"].get(k) == v for k, v in selector.items())
for d in deployments
)
if not found:
problems.append(f"service {s['metadata']['name']}: no pod matches {selector}")
return problems
good = [
{"kind": "Deployment", "metadata": {"name": "harvest-api"}, "spec": {
"replicas": 2,
"template": {"metadata": {"labels": {"app": "harvest-api"}}, "spec": {"containers": [{
"name": "api", "image": "harvest-api:2.1.0",
"readinessProbe": {}, "livenessProbe": {},
"resources": {"requests": {"cpu": "250m", "memory": "256Mi"}}}]}}}},
{"kind": "Service", "metadata": {"name": "harvest-api"}, "spec": {"selector": {"app": "harvest-api"}}},
]
bad = [
{"kind": "Deployment", "metadata": {"name": "harvest-api"}, "spec": {
"replicas": 1,
"template": {"metadata": {"labels": {"app": "harvest-api"}}, "spec": {"containers": [{
"name": "api", "image": "harvest-api",
"readinessProbe": {}, "resources": {"requests": {"cpu": "250m"}}}]}}}},
{"kind": "Service", "metadata": {"name": "harvest"}, "spec": {"selector": {"app": "harvest"}}},
]
print("good:", check(good) or "no problem")
for p in check(bad):
print("-", p)
good: no problem
- harvest-api: fewer than 2 replicas
- harvest-api: image without a precise version (harvest-api)
- harvest-api: livenessProbe missing
- harvest-api: requests.memory missing
- service harvest: no pod matches {'app': 'harvest'}
The bad file would go through kubectl apply with no error: Kubernetes accepts a Deployment with no probes or requests, and a Service that selects nothing. That is the whole point of a checker run automatically, for example in continuous integration, on every change to the manifests.
Your turn
Worked exercise
Worked exercise: the autoscaler rule
Add a rule: every HorizontalPodAutoscaler must target a Deployment that exists among the objects, have a minReplicas of at least 2, and a maxReplicas greater than minReplicas. Write the check_hpa(objects) function and test it on two autoscalers, one of which targets a misspelt name.
Hint 1
{o["metadata"]["name"] for o in objects if o["kind"] == "Deployment"}.Hint 2
spec["scaleTargetRef"]["name"]. Check three conditions and add a message for each one that fails.Show the solution and common mistakes
def check_hpa(objects):
problems = []
deployments = {o["metadata"]["name"] for o in objects if o["kind"] == "Deployment"}
for h in (o for o in objects if o["kind"] == "HorizontalPodAutoscaler"):
name, spec = h["metadata"]["name"], h["spec"]
target = spec["scaleTargetRef"]["name"]
if target not in deployments:
problems.append(f"{name}: targets unknown Deployment “{target}”")
if spec.get("minReplicas", 1) < 2:
problems.append(f"{name}: minReplicas below 2")
if spec["maxReplicas"] <= spec.get("minReplicas", 1):
problems.append(f"{name}: maxReplicas must exceed minReplicas")
return problems
objects = [
{"kind": "Deployment", "metadata": {"name": "harvest-api"}, "spec": {}},
{"kind": "HorizontalPodAutoscaler", "metadata": {"name": "harvest-api"},
"spec": {"scaleTargetRef": {"name": "harvest-api"}, "minReplicas": 2, "maxReplicas": 6}},
{"kind": "HorizontalPodAutoscaler", "metadata": {"name": "reports"},
"spec": {"scaleTargetRef": {"name": "report"}, "minReplicas": 1, "maxReplicas": 1}},
]
for p in check_hpa(objects):
print("-", p)
- reports: targets unknown Deployment “report”
- reports: minReplicas below 2
- reports: maxReplicas must exceed minReplicas
Common mistakes:
- Searching the targeted Deployment in a list with a loop for each autoscaler: a
setdoes the lookup in one operation. - Forgetting the default value of
minReplicas(1 in Kubernetes):spec["minReplicas"]would crash on an autoscaler that does not set it.
Summary
- 1An application fits in a few manifests: ConfigMap, Deployment, Service and autoscaler.
- 2Objects find each other by name (ConfigMap, autoscaler target) or by labels (Service).
- 3Kubernetes accepts risky manifests: an automatic checker enforces the team's rules.
- 4Manifests live in Git, are reviewed and applied automatically: the repository is the source of truth.
Your progress is saved on this device. Create a free account to keep your progress on all your devices.