C.W.K.
Stream
Lesson 07 of 08 · published

Comments & Multi-Document Files

~10 min · yaml, comments, multi-document

Level 0Plaintext
0 XP0/64 lessons0/12 achievements
0/100 XP to next level100 XP to go0% complete

Comments YAML has, JSON doesn't

YAML supports # for line comments. Everything from # to end-of-line is ignored. Comments are not part of the data model — round-tripping with most parsers loses them. (Use ruamel.yaml in Python if comment preservation matters.)

Multi-document files

One file can contain multiple YAML documents, separated by --- on its own line. The end-of-document marker ... is rare but valid. Multi-document files are how Kubernetes ships a Deployment + Service + ConfigMap as one kubectl apply -f target.

Reading multi-document YAML

Most parsers expose a stream/iterator API. PyYAML: yaml.safe_load_all(text). js-yaml: yaml.loadAll(text). yq: yq 'select(.kind == "Service")' multi.yaml.

Principle: use comments to capture the why that the data shape doesn't carry — links to incidents, defaults, when this value should change. Don't restate what the keys already say. # server port next to port: 8000 is noise; # keep below 1024 only on the auth gateway, see RFC-12 is signal.

Code

Comments·yaml
# Top-of-file comment — owner, last review, etc.
version: 1

# Database configuration
database:
  host: localhost
  port: 5432       # PostgreSQL default
  pool_size: 5    # see incident 2025-11-04 — must be ≤ 10
Multi-document file (Kubernetes pattern)·yaml
---
apiVersion: v1
kind: ConfigMap
metadata:
  name: app-config
data:
  ENV: production
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: api
spec:
  replicas: 3
---
apiVersion: v1
kind: Service
metadata:
  name: api
spec:
  ports:
    - port: 80
Reading multi-document YAML in Python·python
import yaml

with open('manifests.yaml') as f:
    docs = list(yaml.safe_load_all(f))

print(f'Loaded {len(docs)} documents')
for doc in docs:
    if doc is None:
        continue
    print(f'  - kind={doc.get("kind")}, name={doc["metadata"]["name"]}')
Filtering with yq·bash
# Just the Service document from a multi-doc file:
yq 'select(.kind == "Service")' manifests.yaml

# Count documents:
yq -s 'length' manifests.yaml

# Replace one document, keep others:
yq '(select(.kind == "Deployment") | .spec.replicas) = 5' manifests.yaml

External links

Exercise

Take a real Kubernetes manifest with multiple documents. Read it with yaml.safe_load_all in Python and count the documents. Then edit one document programmatically (change a replica count, say) and write it back with safe_dump_all. Diff before/after — note the comments are gone. Now retry with ruamel.yaml. The diff is the case for ruamel.

Progress

Progress is local-only — sign in to sync across devices.
Spotted a bug or have feedback on this page?Report an Issue

Comments 0

🔔 Reply notifications (sign in)
Sign inPlease sign in to comment.

No comments yet — be the first.