Common YAML Syntax Errors and How to Fix Them
Identify and fix the most common YAML syntax errors including indentation mistakes, tab characters, invalid characters, unquoted special values, and duplicate keys. Includes examples and solutions.
Detailed Explanation
Common YAML Syntax Errors
YAML's reliance on whitespace and its flexible type system make it prone to subtle errors. Understanding the most common mistakes helps you debug YAML files quickly.
1. Tab Characters
YAML forbids tab characters for indentation. This is the most common error:
# ERROR: tabs used for indentation
server:
host: localhost # Tab character!
Fix: Replace all tabs with spaces. Most editors can be configured to insert spaces when Tab is pressed.
2. Inconsistent Indentation
Sibling keys must be at the same indentation level:
# ERROR: inconsistent indentation
server:
host: localhost
port: 8080 # 3 spaces instead of 2
Fix: Ensure all keys at the same nesting level use identical indentation.
3. Unquoted Special Values
YAML auto-interprets certain strings as non-string types:
# These are NOT strings!
country: NO # Parsed as boolean false
version: 1.0 # Parsed as float, not string "1.0"
port: 0800 # Parsed as octal number
time: 12:30 # Parsed as sexagesimal (base-60) number
Fix: Quote values that should remain strings: country: "NO", version: "1.0"
4. Missing Space After Colon
YAML requires a space after the colon in key-value pairs:
# ERROR: no space after colon
host:localhost
Fix: Always include a space: host: localhost
5. Unescaped Special Characters in Values
Colons, hash signs, and brackets in values need quoting:
# ERROR: colon in value
message: Error: file not found
url: http://example.com # This actually works, but...
regex: [a-z]+ # Parsed as a sequence!
Fix: Quote values containing special characters: message: "Error: file not found"
6. Incorrect List Indentation
List items must be consistently indented:
# ERROR: list item at wrong level
items:
- first # Should be indented under 'items'
- second # Inconsistent with first item
7. Duplicate Keys
While technically valid in the YAML spec, duplicate keys cause unpredictable behavior:
# BAD: duplicate key
database:
host: db1.example.com
host: db2.example.com # Silently overwrites the first
A good YAML validator warns about duplicate keys even though parsers will accept them.
Use Case
YAML syntax error detection is critical in any configuration-driven workflow. A single indentation error in a Kubernetes manifest can prevent a deployment, and an unquoted boolean in a CI config can cause unexpected behavior. Running YAML through a validator before committing catches these issues early and saves debugging time.