YAML Basics Cheat Sheet

YAML is the config language of Docker Compose, GitHub Actions, Kubernetes, CI pipelines, and proxy subscriptions. It looks friendly — indentation instead of braces — and most of its pain comes from the few places where it silently guesses a type you didn't mean. Every example on this page was parsed and checked against a real YAML parser.

A whole file, annotated

One small service definition shows the three building blocks: a mapping (key: value), a sequence (a list), and a scalar (a plain value). Everything else on this page is a variation on these.

# a small service definition
services:
  web:
    image: nginx:1.27
    ports:
      - "80:80"
      - "443:443"
    environment:
      - TZ=Asia/Shanghai
    restart: unless-stopped

Read it like this: services maps to web, which maps to four keys. ports is a list of two strings — quoted, because an unquoted 80:80 would confuse the parser. Two spaces per indent level is the convention; the exact width doesn't matter, but it must be consistent within a block.

Scalars — what your text becomes

YAML doesn't just store text: it infers a type from unquoted values. The table below shows what a parser actually produces — verified, not guessed.

You writeParsed asType
name: huanlog"huanlog"string
count: 4242integer
pi: 3.143.14float
big: 1_0001000integer — underscores are ignored
hex: 0x1F31integer — hex works
bin: 0b1015integer — binary works
enabled: true / True / TRUEtrueboolean
enabled: falsefalseboolean
nothing: null / ~ / (empty)nullnull — an empty value is null too
day: 2026-11-21a datetimestamp — parsers may return a date object, not a string
when: 2026-11-21T09:30:00Za datetimetimestamp with timezone

The rule that saves you: if the value is meant to be text, quote it. version: "1.10" stays the string "1.10"; unquoted, it parses as the float 1.1 and the trailing zero is gone forever. Same for port: "8080" — unquoted, it's the number 8080, and some tools will then refuse it as a string.

Strings: plain, single-quoted, double-quoted

StyleExampleResultNotes
Plainname: Huan Log"Huan Log"Fine for simple text; breaks on leading special characters
Single-quotedname: 'it''s fine'"it's fine"No escapes except doubling the quote: '' → '. Backslashes stay literal
Double-quotedname: "say \"hi\""say "hi"Escape sequences work: \n is a real newline, \" is a quote

When plain strings break: a value starting with *, &, !, |, >, %, @, or backtick is special syntax — quote it. A colon inside a value is fine only when followed by a space or the end of the line: url: http://example.com works, but note: a: b is a syntax error. A # starts a comment only after a space: k: value#x is the literal string "value#x".

Block scalars: multi-line text

For long text — descriptions, scripts, certificates — use | (keep newlines) or > (fold newlines into spaces). The optional + / - controls the final newline, and a digit sets the indent explicitly.

HeaderInput linesResult
msg: |line one
line two
"line one\nline two\n" — newlines kept, one trailing newline
msg: |-line one
line two
"line one\nline two" — trailing newline stripped
msg: |+line one
line two + blank line
"line one\nline two\n\n" — trailing blank lines kept
msg: >a long sentence
wrapped here
"a long sentence wrapped here\n" — lines folded to one, blank lines become \n
msg: >-a long sentence
wrapped here
"a long sentence wrapped here" — folded, no trailing newline
msg: |2content indented 2 spacesExplicit indent — the number is relative to the parent key

Default pick: | for anything where line breaks matter (scripts, keys, addresses), > for prose you want to wrap in the file but read as one paragraph.

Collections: lists, maps, nesting

# a block sequence — one dash per item
fruits:
  - apple
  - banana

# flow style — same thing, on one line
fruits: [apple, banana]
person: {name: Ada, age: 36}

# nesting: indentation is the structure
a:
  b:
    c: 1

# a list of maps — the shape of most real configs
- name: web
  image: nginx
- name: db
  image: postgres

# nested lists
matrix:
  - [1, 2]
  - [3, 4]

# empty collections
empty_list: []
empty_map: {}

Two styles, same data: block style (dashes and indentation) is what humans read; flow style ([] and {}) is what you use for short inline values. A list under a key can sit at the same indent as the key — ports:\n- 80 — which is valid and common in real files, though indenting the dashes one level is easier to read.

Anchors, aliases & merge keys

Define a block once with &name, reuse it with *name, and merge it into another mapping with <<. Local keys override merged ones.

defaults: &defaults
  retries: 3
  timeout: 30

job_a:
  <<: *defaults
  name: a

job_b:
  <<: *defaults
  name: b
  retries: 5

Result: job_a is {retries: 3, timeout: 30, name: a}; job_b is {retries: 5, timeout: 30, name: b} — its own retries: 5 wins over the merged 3. Anchors are also how you keep a long Compose file or CI workflow DRY without copy-pasting whole blocks. One caveat: an anchor must be defined before it is referenced.

Multi-document files

---
name: one
---
name: two

--- starts a document; ... ends one explicitly. A file with several --- separators holds several documents — Kubernetes manifests and test fixtures use this. Most tools load only the first document unless you ask for all of them (in Python: yaml.safe_load_all()). Directives like %YAML 1.2 may appear at the very top, before the first ---, but most parsers ignore them.

Gotchas that break real files

SymptomCauseFix
found character '\t' that cannot start any tokenTabs are forbidden as indentation — YAML is spaces-onlyConvert tabs to spaces; set your editor to insert spaces for YAML
Two keys silently merge into one mappingInconsistent indentation — a key at the wrong depth belongs to the wrong parentPick one indent width (2 spaces) and keep sibling keys aligned
on: true in a GitHub Actions workflow never triggersOlder parsers (PyYAML, YAML 1.1) read unquoted on / yes / no / off as booleans; YAML 1.2 says they are stringsQuote them: "on": true — or write on: true only when you mean a boolean
Version 1.10 becomes 1.1Unquoted numbers are numbers — the trailing zero is lostQuote version strings: version: "1.10"
Octal 0o17 stays a string in one tool, becomes 15 in anotherYAML 1.1 octal is 017; YAML 1.2 octal is 0o17 — parsers disagreeUse decimal, or quote it if the exact text matters
time: 1:30 becomes the number 90YAML 1.1 sexagesimal numbers — some parsers still apply themQuote times: time: "1:30"
One of two identical keys silently disappearsDuplicate keys: most parsers keep only the last value, with no warningSearch for the key before adding it; use a linter that flags duplicates
A value comes out empty when you expected textA key with nothing after the colon is null, not an empty stringWrite key: "" when you mean an empty string
mapping values are not allowed hereA bare colon with no space after it, e.g. note: a: bQuote the value, or restructure it into a nested mapping

Validate before you ship it

YAML fails silently more often than it fails loudly — a wrong type parses fine and breaks at runtime. Check every config before it goes live:

# Python — parse and pretty-print, no dependencies beyond PyYAML
python3 -c "import yaml, sys, json; print(json.dumps(yaml.safe_load(open(sys.argv[1])), indent=2, default=str))" config.yaml

# yq — query it like jq
yq '.services.web.image' docker-compose.yml

# yamllint — style + duplicate-key checks
yamllint config.yaml

For a quick sanity check, paste the file into any online YAML validator — but never paste secrets into a website. The fastest local check is the Python one-liner above: if it prints your data back as JSON, the file parses.

Keep going