{FormJSON}
DevOps & Configuration YAML 1.2 Specification 8 Min Read

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.

Validate or format your YAML configuration
Format indentation, fix tab errors, and convert to JSON with 100% client-side privacy.
Open YAML Studio →

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.

The Cardinal Law of YAML:

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

Frequently Asked Questions

FAQ

What is the difference between literal (|) and folded (>) block scalars in YAML?
The literal style ('|') preserves all newlines and exact formatting verbatim. The folded style ('>') collapses consecutive lines into single spaces, useful for long multi-line paragraphs or descriptions.
What do the chomping indicators '+' and '-' mean?
Strip ('|-') removes all trailing newlines. Keep ('|+') preserves all trailing newlines exactly as typed. Default clip ('|') preserves a single final newline.
How do anchors (&) and aliases (*) work in YAML?
Anchors define a reusable node (&anchor_name), and aliases (*anchor_name) inject that node elsewhere in the document, avoiding duplication in configs like Docker Compose or GitLab CI.