YAML Indentation, Block Scalars, and Syntax Rules Demystified
A reference guide to mastering YAML whitespace mechanics, block multiline strings, and DRY anchors in modern infrastructure configs.
1. Indentation Rules: The Zero-Tab Law
Unlike JSON where whitespace is completely syntactic sugar outside of string literals, whitespace in YAML establishes structure and hierarchy.
ASCII Tab characters (\t) are strictly illegal for indentation in YAML. All nesting must use ASCII space characters (0x20). While any consistent number of spaces is technically valid, the universal industry standard is 2 spaces per indentation level.
2. Literal (|) vs Folded (>) Block Scalars
| Operator | Behavior | Common Use Case |
|---|---|---|
| | (Literal) | Preserves all line breaks verbatim. | Shell scripts, private SSL certificates, SQL queries in ConfigMaps. |
| > (Folded) | Replaces newlines with spaces; preserves empty lines as paragraph breaks. | Long markdown descriptions, email bodies, human-readable documentation. |
| |- (Strip) | Literal block that strips any trailing newlines at the end of the string. | Single-line secrets or base64 keys where a trailing newline would break verification. |
3. DRY Configurations with Anchors (&) and Aliases (*)
In complex Docker Compose or CI/CD pipelines, YAML anchors eliminate duplicate configuration:
# Define base service template with anchor &common_env
x-common-env: &common_env
NODE_ENV: production
LOG_LEVEL: info
services:
web:
image: myapp:v1
environment:
<<: *common_env # Merge alias
PORT: 3000
worker:
image: myapp:v1
environment:
<<: *common_env # Merge alias
QUEUE: tasks