YAML Format Cheat Sheet: Syntax, Comments and Examples

November 11, 2026 · 11 min read

YAML Format Cheat Sheet: Syntax, Comments and Sample Files

The YAML format stores data as indented key: value pairs, - list items and # comments in a plain text file. This page puts the core constructs in one table. Then it covers the indentation, quoting and comment rules that break files, plus four sample files to copy.

YAML Format Cheat Sheet: Core Constructs in One Table

Each row shows the syntax and what a parser hands back, written in JSON notation so the type is obvious. The rules come from the YAML 1.2.2 specification, the current revision.

ConstructSyntaxParses as
Key/value pairname: web{"name": "web"}
Nested mapdb: with host: localhost indented below{"db": {"host": "localhost"}}
List item- redis indented under a key["redis"]
Flow map{x: 1, y: 2}{"x": 1, "y": 2}
Flow list[a, b]["a", "b"]
Plain stringtitle: Hello world"Hello world"
Single-quoted string'it''s here'"it's here"
Double-quoted string"line one\nline two"text with a real line break
Integerport: 80808080
Floatratio: 0.750.75
Booleandebug: truetrue
Nullcache: ~, cache: null or cache:null
Comment# notenothing, the parser skips it
Document start / end--- / ...separates documents
Anchor / alias&base / *basereuses the same node
Merge key<<: *basecopies the anchored keys in

A list needs only one row because it's just a value whose items each start with - :

services:
  - web
  - redis

That parses as {"services": ["web", "redis"]}. The same rules cover the YAML block at the top of a Markdown file, which our Markdown front matter guide explains field by field.

What Are the Indentation Rules for YAML?

The YAML format uses spaces, never tabs, to show which value belongs to which key. The spec says tab characters must not be used in indentation. Any number of spaces works as long as siblings line up exactly and children sit further right than their parent. Two spaces is the common convention.

server:
  host: 0.0.0.0
  port: 8080
  origins:
  - https://example.com
  - https://admin.example.com

This gives server three keys, and origins holds a list of two URLs. Notice the list items sit at the same column as origins. That's valid: a block list may start at its parent key's indent or further in, and both parse identically. Pick one style per file. Our YAML list syntax guide covers flow arrays, nested lists and lists of objects.

If port had three spaces instead of two, the parser would reject the file, because it no longer aligns with host. YAML treats indentation as structure, which is a different job from the 4-space code indent you meet in Markdown (see Markdown indentation for that side).

Keys, Values and Nesting in YAML Syntax

Every mapping entry is a key, a colon, a space, then the value. The space matters. port: 8080 is a pair, but port:8080 is a single plain string, and inside a mapping it triggers an error like could not find expected ':'.

app:
  name: billing
  owner:
    team: payments
    email: pay@example.com
  url: https://billing.example.com:8443

Nesting goes as deep as you like. The url value is fine unquoted because a colon only counts as a separator when a space follows it. YAML also has a flow style, {name: billing} and [a, b], which looks like JSON because YAML 1.2 set out to be a strict superset of JSON. For when to pick each format, see our YAML vs JSON comparison.

Keys inside one mapping must be unique, per the spec. Parsers disagree on enforcement, though. In our tests PyYAML 6.0.3 kept the last value without a warning, while the yaml package for JavaScript (2.8.4) threw an error. Don't rely on either behaviour.

Strings, Numbers, Booleans and Null: When to Quote

Unquoted (plain) values get a type from their shape. Usually that's what you want, but it's also where most surprises come from, especially with older YAML 1.1 parsers such as PyYAML.

release: 1.10       # float 1.1, the trailing zero is gone
version: "1.10"     # string "1.10"
zip: 02134          # 2134 in YAML 1.2, octal 1116 in YAML 1.1
country: NO         # false in YAML 1.1, string "NO" in 1.2
enabled: yes        # true in YAML 1.1, string "yes" in 1.2
middle_name:        # null
path: 'C:\temp'     # backslash kept as typed
tabbed: "C:\temp"   # \t becomes a real tab character

In the YAML 1.2 core schema only true and false (plus True/TRUE and False/FALSE) are booleans. YAML 1.1 also treats yes, no, on, off, y and n as booleans, which is why a country code of NO can turn into false.

Quote a value when it contains : or #. Also quote it when it starts with a reserved indicator character, such as *, &, !, %, @, {, [, |, >, ', " or a backtick. Double quotes process backslash escapes like \n and \t. Single quotes process none; the only escape is doubling the quote, as in 'it''s'.

We prefer quoting any value that isn't plainly a number or true/false. It costs two characters and removes the guesswork. For long text, a key followed by | keeps line breaks, and > folds them into spaces. Our YAML multiline string guide covers both, plus the chomping indicators.

How Do You Comment in YAML?

Comments in YAML start with # and run to the end of the line. You can put one on its own line or after a value, and the parser discards it. The spec adds one rule people miss: a comment must be separated from other tokens by whitespace.

# Database settings
db:
  host: localhost   # inline comment, needs the space before #
  ticket: BUG#7     # no space before #, so the value is "BUG#7"
  owner: ops #team  # the value is just "ops"
  color: "#ff0000"  # inside quotes, # is plain text

YAML has no block or multi-line comment syntax. To comment out several lines, put # at the start of each one. Most code editors do this for a whole selection. In VS Code the Toggle Line Comment command is Ctrl+/ on Windows and Linux and Cmd+/ on macOS, per VS Code's keyboard shortcut reference.

services:
  web:
    image: nginx:1.27
#  cache:
#    image: redis:7

Docker Compose files, GitHub Actions workflows and Kubernetes manifests all take the same # comments, since they're plain YAML. The spec calls YAML comments a presentation detail, so they never reach your program. That also means they can vanish: PyYAML drops them when it loads and re-dumps a file, while ruamel.yaml is built to keep them on a round trip. Markdown comments work differently, using HTML syntax; see Markdown comments.

Multiple Documents, Anchors and Aliases

Three dashes, ---, start a document and three dots, ..., end one. A file with a single document needs neither. Several documents can share one file, and Kubernetes manifests often bundle a Deployment and a Service that way.

defaults: &defaults
  adapter: postgres
  host: localhost
development:
  <<: *defaults
  database: dev_db
test:
  <<: *defaults
  database: test_db

&defaults names a node, *defaults reuses it, and << copies its keys into the current map. Both development and test end up with adapter and host plus their own database.

The << merge key comes from the YAML 1.1 type repository, not the 1.2 core schema. Docker Compose supports it, as its fragments reference shows. Some 1.2 parsers only apply it when you switch on an option.

Sample YAML Files You Can Copy

Each sample YAML file below is complete and valid, with comments on the lines that need explaining. Together these YAML examples cover the config files you're most likely to edit: an app config, a Compose file, a CI workflow and a Kubernetes object. Change the values and keep the structure. The samples use both .yaml and .yml, and our YAML explainer covers which extension to pick.

1. App config (config.yaml)

app:
  name: inventory
  version: "2.4.0"      # quoted so it stays a string
  debug: false
  log_file: null
database:
  host: db.internal
  port: 5432
features:
  - search
  - export

This file nests two maps and a list, and it uses a boolean, a null and a quoted version string.

2. Docker Compose (compose.yaml)

services:
  web:
    image: nginx:1.27
    ports:
      - "8080:80"        # quoted: host:container
    environment:
      APP_ENV: production
  cache:
    image: redis:7

It defines two containers. There's no top-level version key, because Docker's docs mark it obsolete and Compose only warns about it. Port mappings are quoted because Docker's docs say HOST:CONTAINER values should always be strings, to avoid YAML's base-60 number parsing.

3. GitHub Actions workflow (.github/workflows/ci.yml)

name: CI
on:
  push:
    branches: [main]
jobs:
  test:
    runs-on: ubuntu-latest   # a GitHub-hosted runner
    steps:
      - uses: actions/checkout@v7
      - run: npm ci
      - run: npm test

This runs the tests on every push to main. GitHub reads on as the trigger key. A YAML 1.1 parser such as PyYAML loads it as the boolean true, though, which matters if a Python script reads your workflows.

4. Kubernetes ConfigMap (configmap.yaml)

apiVersion: v1
kind: ConfigMap
metadata:
  name: app-settings
data:
  LOG_LEVEL: "info"
  MAX_RETRIES: "3"     # quoted: data values are strings

The data field is designed to hold UTF-8 strings, so quote numbers and booleans. Apply it with kubectl apply -f configmap.yaml.

YAML Formatting Mistakes That Break or Quietly Change a File

Some YAML format mistakes stop the parser cold. Others are worse: the file loads, but with the wrong value. Here's each one as a broken and fixed pair.

MistakeBrokenFixed
Tab used for indentationa tab before port: 80two spaces before port: 80
No space after the colonport:8080port: 8080
Colon and space inside a valuemotto: Rule 1: test firstmotto: "Rule 1: test first"
Unquoted hex colorcolor: #ff0000 (loads as null)color: "#ff0000"
Same key twicetwo port: lines in one mapone port: line
Version number as a floatversion: 1.10version: "1.10"
YAML 1.1 boolean wordsanswer: noanswer: "no"
List item mixed into a map- redis at the same level as name: webmove the list under its own key

No cheat sheet, this one included, can promise how every parser behaves. PyYAML follows YAML 1.1, while many newer libraries follow 1.2, so the same file can load differently. Test with the exact tool that will read the file.

Keep this YAML format reference open the next time a config file refuses to load. Check the indentation, quote anything ambiguous, and put a space before every inline #. If your YAML sits at the top of a Markdown file, the front matter generator builds that block for you. Then write the Markdown below it in the editor.