BudiBadu Logo
Samplebadu

YAML by Example: Indentation Rules

1.2

Understanding spaces and structure. YAML relies on proper indentation.

Code

# Correct indentation (2 spaces)
database:
  host: localhost
  port: 5432
  credentials:
    username: admin
    password: secret

# Also valid (4 spaces) - just be consistent
server:
    name: production
    region: us-east-1

# Wrong - mixing tabs and spaces causes errors
# Never use tab characters!

# Wrong - inconsistent spacing
config:
  option1: value
   option2: value  # Extra space breaks structure

Explanation

YAML requires spaces for indentation and explicitly forbids tabs. Using tabs will cause parsing errors. Most editors can be configured to insert spaces when you press Tab. The standard is 2 spaces per indentation level, but you can use 4 or more as long as you stay consistent throughout the file.

Child elements must be indented more than their parent. The exact number of spaces doesn't matter, just that children have more indentation than parents. Inconsistent indentation is the most common YAML error, so pay attention to spacing when nesting structures.

Code Breakdown

2-5
Each level is indented 2 more spaces than its parent.
8-10
This uses 4 spaces per level, which is also valid.