Objects & Manifests
Everything in Kubernetes is an object: a Pod, a Service, a Namespace, a Node. Every object, whatever its kind, has the same top-level shape:
apiVersion: v1 # API group/version that defines this kind
kind: Pod # the type of object
metadata: # identity: name, namespace, labels, annotations
name: hello
namespace: default
labels:
app: hello
spec: # desired state: what YOU want
containers:
- name: hello
image: busybox:1.37
command: ["sh", "-c", "echo hello && sleep 3600"]
status: # actual state: written by Kubernetes, never by you
phase: Running| Field | Who writes it | Meaning |
|---|---|---|
apiVersion |
you | v1 for core kinds, group/version for others (apps/v1, batch/v1, networking.k8s.io/v1) |
kind |
you | Pod, Deployment, Service, … |
metadata |
you (+ system fields like uid, resourceVersion, creationTimestamp) |
Name and organisation |
spec |
you | The desired state |
status |
controllers | The observed state |
YAML in five minutes
Manifests are YAML, a human-friendly superset of JSON. The rules that trip people up:
- Indentation is spaces only (2 is conventional) and it defines the structure.
key: valuemakes a mapping,- itemmakes a list item.---separates several documents in one file.- Quotes are optional, but values like
yes,no,on,1.10and08may not be what you expect. Quote version numbers and anything that must be a string.
import yaml
text = """
port: 8080
debug: yes
version: 1.10
quoted_version: "1.10"
tag: "08"
items:
- one
- two
nested:
key: value
"""
for key, value in yaml.safe_load(text).items():
print(f"{key:15} {value!r:20} {type(value).__name__}")port 8080 int
debug True bool
version 1.1 float
quoted_version '1.10' str
tag '08' str
items ['one', 'two'] list
nested {'key': 'value'} dict
Warning:
version: 1.10became the float1.1, and PyYAML (a YAML 1.1 parser) turnedyesintoTrue. Kubernetes uses a YAML 1.2-style parser whereyesstays a string, but the lesson is the same: quote anything that must be a string, such as environment variable values ("true","8080").
Multi-document files
You can keep related objects in one file separated by ---. kubectl apply -f app.yaml creates them all:
import yaml
app_yaml = """
apiVersion: v1
kind: Namespace
metadata:
name: shop
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: api
namespace: shop
spec:
replicas: 2
---
apiVersion: v1
kind: Service
metadata:
name: api
namespace: shop
"""
for doc in yaml.safe_load_all(app_yaml):
ns = doc["metadata"].get("namespace", "-")
print(f"{doc['apiVersion']:8} {doc['kind']:11} {doc['metadata']['name']:5} ns={ns}")v1 Namespace shop ns=-
apps/v1 Deployment api ns=shop
v1 Service api ns=shop
Validating before you apply
The API server rejects manifests with missing fields or wrong types. You can catch the most common mistakes earlier with a simple checker. This one verifies the four required top-level fields, a valid DNS-1123 name (lowercase letters, digits and -, starting and ending with an alphanumeric, at most 63 characters for labels/most names) and that every container has a name and an image:
import re
import yaml
NAME = re.compile(r"^[a-z0-9]([-a-z0-9]*[a-z0-9])?quot;)
def check(doc):
problems = []
for field in ("apiVersion", "kind", "metadata"):
if field not in doc:
problems.append(f"missing {field}")
name = doc.get("metadata", {}).get("name", "")
if not NAME.match(name) or len(name) > 63:
problems.append(f"invalid name {name!r}")
if doc.get("kind") == "Pod":
for i, c in enumerate(doc.get("spec", {}).get("containers", [])):
if "image" not in c:
problems.append(f"containers[{i}] has no image")
if "name" not in c:
problems.append(f"containers[{i}] has no name")
return problems or ["ok"]
files = {
"good.yaml": "apiVersion: v1\nkind: Pod\nmetadata: {name: web}\nspec:\n containers: [{name: web, image: nginx:1.27}]",
"bad-name.yaml": "apiVersion: v1\nkind: Pod\nmetadata: {name: My_Web}\nspec:\n containers: [{name: web, image: nginx}]",
"no-image.yaml": "kind: Pod\nmetadata: {name: web}\nspec:\n containers: [{name: web}]",
}
for filename, text in files.items():
print(filename, "->", "; ".join(check(yaml.safe_load(text))))good.yaml -> ok
bad-name.yaml -> invalid name 'My_Web'
no-image.yaml -> missing apiVersion; containers[0] has no image
In a real cluster, the server-side equivalents are:
kubectl apply -f app.yaml --dry-run=server # full validation by the API server, nothing stored
kubectl explain deployment.spec.strategy # documentation for any fieldspec vs status, live
After you apply a manifest, kubectl get -o yaml shows the object with fields the system added: uid, resourceVersion, creationTimestamp, defaults you didn't write (like restartPolicy: Always) and the status block. Controllers continuously make status converge towards spec.
Tip: Never copy
status,uidorresourceVersionback into your files. Your Git copy should contain only what you decided.
Test yourself
Which section of an object do controllers write to report the actual state?
- metadata
- spec
- status
- apiVersion
What is the apiVersion of a Deployment?
- v1
- apps/v1
- deployments/v1
- k8s.io/v1
Which name is a valid Kubernetes object name?
- My_App
- -web
- web-api-2
- web.API