One YAML file's journey: from your first key to a running cluster
Follow a single config from `key: value` through Docker Compose, Kubernetes and CI — and learn the indentation rules, type traps and habits that keep YAML from breaking production.
Open any modern DevOps repository and you'll find the same thing everywhere: Kubernetes manifests, Ansible playbooks, GitHub Actions workflows, Argo CD applications, Docker Compose files. Different tools, one language. YAML.
Most people learn it by copy-paste — and then lose an afternoon to a stray tab or a country code that turned into false. This article takes a different route. We'll follow one small file on its journey: from a single line, to an app on your laptop, to three replicas in a cluster, to a pipeline that checks it on every commit. You'll learn each rule at the moment it starts to matter.
- Your first keyA
key: valuepair — the whole language grows from this - StructureIndentation, lists and lists of maps describe anything nested
- TypesUnquoted values get guessed — and sometimes guessed wrong
- Docker ComposeThe same file describes an app with a web server and a database
- KubernetesManifests declare desired state; the cluster makes it real
- YAML as codeAnchors, linting, validation and secrets keep it safe in Git
Stop 1 · Why YAML won the config wars
YAML stands for YAML Ain't Markup Language. It was first released in 2001, at a time when XML and JSON were the obvious choices. It was designed for one thing they weren't: humans writing and reading configuration.
Here is the same user in all three formats:
<user>
<name>John Doe</name>
<age>30</age>
<job>Engineer</job>
</user>{
"user": { "name": "John Doe", "age": 30, "job": "Engineer" }
}# The same user, in YAML
user:
name: John Doe
age: 30
job: EngineerJSON is excellent for machines talking to machines — APIs, logs, payloads. But for a file a human edits at 2 a.m., it has two problems: no comments, and a lot of syntax noise (quotes on every key, braces, and the trailing comma that breaks the whole file).
| YAML | JSON | XML | |
|---|---|---|---|
| Human readability | High | Medium | Low |
| Comments | Yes (#) | No | Yes (<!-- -->) |
| Syntax overhead | Low (indentation) | Medium (braces, quotes) | High (tags) |
| Best at | Config, Infrastructure as Code | APIs, data exchange | Documents, legacy systems |
One more reason YAML spread so quickly: YAML 1.2 is a superset of JSON. Any valid JSON document is also valid YAML. Kubernetes could keep a JSON API at its core and offer YAML manifests on top, with the same parser reading both.
[!NOTE] That's also why you can paste
{"replicas": 3}into a YAML file and it works. Flow style ({}and[]) is legal YAML — it's just rarely the most readable choice.
Stop 2 · The grammar: indentation is structure
YAML has no braces and no closing tags. Whitespace is the structure. Three rules cover almost everything:
- Spaces only — never tabs. The YAML spec forbids tabs for indentation, because editors disagree on how wide a tab is.
- Be consistent. The number of spaces isn't fixed, but siblings must line up exactly. The community standard is two spaces per level.
- A colon needs a space after it.
key: valueis a pair;key:valueis just a string.
Maps: key-value pairs
A mapping is a dictionary, an object, a hash map. Indent a block under a key to nest it:
app:
name: checkout
port: 8080
database:
host: db
name: shopLists: one item per dash
A sequence is a list. Each item starts with a dash and a space:
regions:
- eu-west-1
- us-east-1Lists of maps: the shape of every DevOps file
This is the pattern you'll see in every Compose file, manifest and pipeline — a list of things, where each thing has several fields. The dash starts a new item; the keys indented under it belong to that item.
users:
- name: Alice
role: engineer
- name: Bob
role: analyst- users:A key whose value is a list
- - name: AliceThe dash starts item one — a map
- role: engineerSame indentation as
name, so it belongs to Alice - - name: BobA new dash, a new item
Stop 3 · Types: when YAML guesses wrong
You never declare types in YAML. The parser looks at each unquoted value and guesses: number, boolean, null or string. Usually it's right. Sometimes it's very wrong — and silently so.
Watch a real parser read three innocent-looking lines:
$ cat app.yaml
country: NO
version: 1.10
port: 8080
$ python3 -c 'import yaml; print(yaml.safe_load(open("app.yaml")))'
{'country': False, 'version': 1.1, 'port': 8080}
# Norway became False, and version 1.10 became the number 1.1Two bugs in three lines:
- The Norway problem. YAML 1.1 treats
yes,no,onandoff(in any case) as booleans. YAML 1.2 fixed this — onlytrueandfalseare booleans — but many widely used parsers, including PyYAML (which Ansible uses), still follow the 1.1 rules. - Version numbers aren't numbers.
1.10is parsed as a float, and the trailing zero disappears. Your app asks for version1.1.
The fix is boring and reliable: quote any string that could look like something else.
country: "NO"
version: "1.10"
port: 8080 # a real number, so leave it unquoted
zip_code: "02134" # leading zeros matter, so quote itIf you need to be explicit, a type tag forces the type: version: !!str 1.10. In practice, quotes are clearer to the next reader.
[!TIP] Booleans: write
trueandfalse— lowercase, unquoted — and nothing else. Every parser, 1.1 or 1.2, agrees on those two.
Stop 4 · Multi-line strings: scripts and long text
Sooner or later your file needs to carry a shell script, a certificate or a long description. YAML has two block styles for that.
Literal (|) keeps every newline — exactly what you want for scripts:
script: |
#!/bin/bash
set -euo pipefail
echo "Deploying $APP_VERSION"Folded (>) joins lines with spaces — for long text you want to wrap in the file but read as one paragraph. A blank line still starts a new paragraph:
description: >
This service handles checkout for the shop.
It talks to the payments API and the orders database.
On-call: #team-checkoutThat value becomes "This service handles checkout for the shop. It talks to the payments API and the orders database.\nOn-call: #team-checkout\n".
Add a chomping indicator to control the final newline: |- and >- strip it, |+ and >+ keep all trailing newlines.
Stop 5 · Docker Compose: the file becomes an app
Now our file does real work. Docker Compose reads a compose.yaml and starts every container your app needs. Here is a web app and a PostgreSQL database — every construct from stops 2 to 4 is in it:
# compose.yaml
services:
web:
build:
context: ./app
args:
APP_ENV: production
image: shop-web:latest
ports:
- "8080:80" # HOST:CONTAINER — quoted, so it's never misread
environment:
DB_HOST: db # the service name is also its hostname
networks: [frontend, backend]
depends_on:
db:
condition: service_healthy # wait until the database is ready
db:
image: postgres:17-alpine
environment:
POSTGRES_USER: shop
POSTGRES_PASSWORD_FILE: /run/secrets/db_password
secrets: [db_password]
volumes:
- db-data:/var/lib/postgresql/data
networks: [backend] # not on frontend: unreachable from outside
healthcheck:
test: ["CMD-SHELL", "pg_isready -U shop"]
interval: 10s
timeout: 5s
retries: 5
volumes:
db-data:
networks:
frontend:
backend:
secrets:
db_password:
file: ./secrets/db_password.txt # kept out of GitA few things worth noticing:
- No
version:key. It's obsolete — current Docker Compose ignores it and prints a warning. Old tutorials still include it. - Service names are hostnames.
webreaches the database atdb, with no IP addresses anywhere. - Two networks. The database sits only on
backend, so nothing outside the app can reach it. - The password isn't in the file. It's read from a secret file that never goes into Git.
The depends_on trap
depends_on: [db] on its own only means start the db container first. It doesn't wait for PostgreSQL to accept connections — so the web app boots, connects too early and crashes. condition: service_healthy plus a healthcheck makes Compose wait for real readiness:
- Start dbCompose starts the database container first
- Health check
pg_isreadyruns every 10 seconds until it succeeds - HealthyThe db container is marked healthy
- Start webOnly now does Compose start the web container — the database is ready
Check the file before you run it — docker compose config parses it and prints the fully resolved result, or the exact line that's wrong:
$ docker compose config --quiet && echo "compose.yaml is valid" compose.yaml is valid $ docker compose up -d [+] Running 5/5 ✔ Network shop_frontend Created ✔ Network shop_backend Created ✔ Volume "shop_db-data" Created ✔ Container shop-db-1 Healthy ✔ Container shop-web-1 Started
Stop 6 · Kubernetes: the file declares desired state
Compose runs your app on one machine. Kubernetes runs it across a cluster — and here YAML changes role. You no longer describe steps; you declare the state you want, and the cluster works continuously to make it true.
Every Kubernetes object, whatever it is, has the same four top-level keys:
| Key | What it says | Example |
|---|---|---|
apiVersion | Which API version defines this object | apps/v1, v1 |
kind | What type of object it is | Deployment, Service |
metadata | Its name, namespace and labels | name: web |
spec | The desired state | replicas, image, ports |
The Deployment: run three copies
# deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: web
spec:
replicas: 3
selector:
matchLabels:
app: web # manage every pod with this label...
template:
metadata:
labels:
app: web # ...and stamp this label on every new pod
spec:
containers:
- name: web
image: shop-web:1.4.2
ports:
- containerPort: 80The template is a cookie-cutter for pods. The selector tells the Deployment which pods are its own. They must match — the API server rejects a Deployment whose selector doesn't match its own template's labels.
The Service: one stable address
Pods come and go, and every new pod gets a new IP. A Service gives them one stable name and address:
# service.yaml
apiVersion: v1
kind: Service
metadata:
name: web
spec:
type: ClusterIP # internal only; see the Services article for the other types
selector:
app: web # send traffic to every ready pod with this label
ports:
- port: 80
targetPort: 80 # the containerPort aboveNotice what's missing: the Deployment and the Service never mention each other. The only thing that links them is a label.
- DeploymentCreates pods stamped with
app: web - PodsThree pods carry the label, each with its own changing IP
- ServiceSelects
app: weband tracks every ready pod automatically - TrafficRequests to
webare spread across whichever pods exist right now
That loose coupling is what makes Kubernetes resilient — and it's also its most common failure. One typo in a label and the Service has nowhere to send traffic. I walk through exactly that bug in Kubernetes Services, from ClusterIP to Ingress. And if you want to know what happens after you apply these files, read what really happens when you run kubectl apply.
Before anything reaches the cluster, ask the API server to check it — a server-side dry run validates the YAML against the real schemas and admission rules, and changes nothing:
$ kubectl apply -f k8s/ --dry-run=server deployment.apps/web created (server dry run) service/web created (server dry run) $ kubectl apply -f k8s/ deployment.apps/web created service/web created
Stop 7 · YAML as code: DRY, linted and secret-free
By now our file is infrastructure. It deserves the same care as application code.
Don't repeat yourself: anchors and aliases
Copy the same ten lines into five places and you've built five places to forget an update. YAML has a built-in fix:
&name— an anchor labels a value.*name— an alias reuses it.<<: *name— the merge key copies an anchored map's keys into the current map; any key you write locally wins.
Docker Compose supports all three, and ignores any top-level key starting with x-, which makes a perfect home for shared blocks:
x-app-defaults: &app-defaults
restart: unless-stopped
logging:
driver: json-file
options:
max-size: "10m"
environment: &common-env
LOG_LEVEL: info
TZ: UTC
services:
api:
<<: *app-defaults
image: shop-api:1.4.2
worker:
<<: *app-defaults
image: shop-worker:1.4.2
environment:
<<: *common-env
LOG_LEVEL: debug # overrides the anchored value for this service only- &app-defaultsThe shared block is defined once, under an
x-key Compose ignores - <<: *app-defaults
apiandworkerboth merge in restart policy, logging and environment - Local override
workermerges*common-env, then setsLOG_LEVEL: debug— local keys win
[!WARNING] The merge key
<<comes from YAML 1.1 and isn't supported everywhere. Docker Compose and GitLab CI accept it; GitHub Actions supports anchors and aliases but not merge keys. Check your tool before you rely on it.
Lint every file, every time
A linter is a unit test for YAML. yamllint catches syntax errors, tabs, inconsistent indentation, duplicate keys and the truthy values from stop 3:
$ pipx install yamllint installed package yamllint $ yamllint k8s/ compose.yaml k8s/deployment.yaml 14:1 error syntax error: found character '\t' that cannot start any token (syntax) compose.yaml 9:15 warning truthy value should be one of [false, true] (truthy) # Fix the tab and the yes/no, then run it again — no output means clean $ yamllint k8s/ compose.yaml
Put the rules in a .yamllint.yaml at the root of the repo so everyone — and CI — uses the same ones:
# .yamllint.yaml
extends: default
rules:
line-length:
max: 120
level: warning
indentation:
spaces: 2
indent-sequences: consistent
truthy:
allowed-values: ["true", "false"]Git is the source of truth
Your YAML is your infrastructure, so it lives in Git — and every change goes through the same path as code:
- BranchChange the YAML on a branch, never directly on the server
- Pull requestA teammate reviews the diff: which port, which image, why
- CI checks
yamllint,docker compose configandkubectl apply --dry-run=serverrun automatically - MergeMain is now the single source of truth for what should be running
- DeployA pipeline or a GitOps tool such as Argo CD applies it — and
git revertis your rollback
You get history for free: git log shows every change, and git blame tells you who opened that port and when.
Never commit a secret
Passwords, API keys and private keys never go in a YAML file in Git. The file should reference a secret, never contain it.
- Docker Compose: use
secrets:with a file kept out of Git, as in stop 5. - Kubernetes: a
Secretobject is only base64-encoded, not encrypted — anyone who can read the YAML can decode it. Use an external store such as HashiCorp Vault or your cloud's secret manager (with the External Secrets Operator), or encrypt the files with Sealed Secrets or SOPS before they reach Git.
Keep files small and readable
- One concern per file:
deployment.yaml,service.yaml,configmap.yaml. - Descriptive names:
name: checkout-api, notname: srv1. - Comments explain why, not what:
# 120s: the payments API is slow to warm up.
Journey's end: the cheat sheet
Our file started as one key: value line. It became an app on a laptop, three replicas in a cluster, and a pull request checked by CI on every commit. The language didn't change along the way — only what it described.
| Rule | Do | Don't |
|---|---|---|
| Indentation | 2 spaces, consistently | Tabs, ever |
| Pairs | key: value | key:value |
| Ambiguous strings | country: "NO", version: "1.10" | Trust the parser to guess |
| Booleans | true / false | yes, no, on, off |
| Scripts | | literal block | One long line with \n |
| Repetition | Anchors, x- blocks, merge keys where supported | Copy-paste |
| Checks | yamllint, docker compose config, kubectl apply --dry-run=server | "It looked fine" |
| Secrets | Reference a secret store | Commit the value |
Learn this grammar once and you can read every tool in the DevOps stack — one indentation at a time.
Further reading: the YAML 1.2 specification, the Compose file reference, the Kubernetes objects guide and the yamllint documentation.