Back to articles
DevOps FoundationsFrom the archive3 Dec 2026

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.

#yaml#devops#kubernetes#docker#ci-cd

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.

  1. Your first keyA key: value pair — the whole language grows from this
  2. StructureIndentation, lists and lists of maps describe anything nested
  3. TypesUnquoted values get guessed — and sometimes guessed wrong
  4. Docker ComposeThe same file describes an app with a web server and a database
  5. KubernetesManifests declare desired state; the cluster makes it real
  6. 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:

xml
<user>
  <name>John Doe</name>
  <age>30</age>
  <job>Engineer</job>
</user>
json
{
  "user": { "name": "John Doe", "age": 30, "job": "Engineer" }
}
yaml
# The same user, in YAML
user:
  name: John Doe
  age: 30
  job: Engineer

JSON 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).

YAMLJSONXML
Human readabilityHighMediumLow
CommentsYes (#)NoYes (<!-- -->)
Syntax overheadLow (indentation)Medium (braces, quotes)High (tags)
Best atConfig, Infrastructure as CodeAPIs, data exchangeDocuments, 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:

  1. Spaces only — never tabs. The YAML spec forbids tabs for indentation, because editors disagree on how wide a tab is.
  2. Be consistent. The number of spaces isn't fixed, but siblings must line up exactly. The community standard is two spaces per level.
  3. A colon needs a space after it. key: value is a pair; key:value is 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:

yaml
app:
  name: checkout
  port: 8080
  database:
    host: db
    name: shop

Lists: one item per dash

A sequence is a list. Each item starts with a dash and a space:

yaml
regions:
  - eu-west-1
  - us-east-1

Lists 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.

yaml
users:
  - name: Alice
    role: engineer
  - name: Bob
    role: analyst
  1. users:A key whose value is a list
  2. - name: AliceThe dash starts item one — a map
  3. role: engineerSame indentation as name, so it belongs to Alice
  4. - 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:

terminal
$ 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.1

Two bugs in three lines:

  • The Norway problem. YAML 1.1 treats yes, no, on and off (in any case) as booleans. YAML 1.2 fixed this — only true and false are booleans — but many widely used parsers, including PyYAML (which Ansible uses), still follow the 1.1 rules.
  • Version numbers aren't numbers. 1.10 is parsed as a float, and the trailing zero disappears. Your app asks for version 1.1.

The fix is boring and reliable: quote any string that could look like something else.

yaml
country: "NO"
version: "1.10"
port: 8080            # a real number, so leave it unquoted
zip_code: "02134"     # leading zeros matter, so quote it

If 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 true and false — 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:

yaml
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:

yaml
description: >
  This service handles checkout for the shop.
  It talks to the payments API and the orders database.

  On-call: #team-checkout

That 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:

yaml
# 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 Git

A 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. web reaches the database at db, 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:

  1. Start dbCompose starts the database container first
  2. Health checkpg_isready runs every 10 seconds until it succeeds
  3. HealthyThe db container is marked healthy
  4. 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:

terminal
$ 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:

KeyWhat it saysExample
apiVersionWhich API version defines this objectapps/v1, v1
kindWhat type of object it isDeployment, Service
metadataIts name, namespace and labelsname: web
specThe desired statereplicas, image, ports

The Deployment: run three copies

yaml
# 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: 80

The 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:

yaml
# 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 above

Notice what's missing: the Deployment and the Service never mention each other. The only thing that links them is a label.

  1. DeploymentCreates pods stamped with app: web
  2. PodsThree pods carry the label, each with its own changing IP
  3. ServiceSelects app: web and tracks every ready pod automatically
  4. TrafficRequests to web are 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:

terminal
$ 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:

yaml
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
  1. &app-defaultsThe shared block is defined once, under an x- key Compose ignores
  2. <<: *app-defaultsapi and worker both merge in restart policy, logging and environment
  3. Local overrideworker merges *common-env, then sets LOG_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:

terminal
$ 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:

yaml
# .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:

  1. BranchChange the YAML on a branch, never directly on the server
  2. Pull requestA teammate reviews the diff: which port, which image, why
  3. CI checksyamllint, docker compose config and kubectl apply --dry-run=server run automatically
  4. MergeMain is now the single source of truth for what should be running
  5. DeployA pipeline or a GitOps tool such as Argo CD applies it — and git revert is 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 Secret object 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, not name: 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.

RuleDoDon't
Indentation2 spaces, consistentlyTabs, ever
Pairskey: valuekey:value
Ambiguous stringscountry: "NO", version: "1.10"Trust the parser to guess
Booleanstrue / falseyes, no, on, off
Scripts| literal blockOne long line with \n
RepetitionAnchors, x- blocks, merge keys where supportedCopy-paste
Checksyamllint, docker compose config, kubectl apply --dry-run=server"It looked fine"
SecretsReference a secret storeCommit 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.