YAML Indentation Styles: 2-Space vs 4-Space
Compare 2-space and 4-space YAML indentation styles. Learn which tools and ecosystems prefer which style, and how to convert between them with a YAML formatter.
Detailed Explanation
YAML Indentation: Choosing the Right Style
YAML uses indentation to represent structure, and the choice of indentation width affects readability, file size, and ecosystem compatibility. The two most common styles are 2-space and 4-space indentation.
2-Space Indentation
Two-space indentation is the de facto standard in the cloud-native ecosystem:
apiVersion: apps/v1
kind: Deployment
metadata:
name: my-app
labels:
app: my-app
spec:
replicas: 3
template:
spec:
containers:
- name: app
image: my-app:latest
ports:
- containerPort: 8080
Used by: Kubernetes, Docker Compose, Helm, GitHub Actions, Prettier, most YAML linters
4-Space Indentation
Four-space indentation provides more visual separation between nesting levels:
- hosts: webservers
tasks:
- name: Install nginx
apt:
name: nginx
state: present
- name: Start nginx
service:
name: nginx
state: started
Used by: Ansible (historically), SaltStack, some Python ecosystem tools
Why Indentation Matters
Unlike most programming languages where indentation is purely cosmetic, YAML indentation is syntactically significant:
- Incorrect indentation changes document structure
- Mixed indentation within a file causes parse errors
- Tabs are explicitly forbidden in YAML (the spec requires spaces only)
List Item Indentation
One area of frequent confusion is how list items (-) relate to their parent key:
# Style A: list items at same level as key content
items:
- first
- second
# Style B: list items indented under key
items:
- first
- second
Both are valid YAML. Style A (indented -) is more common and recommended by most linters.
Converting Between Styles
A YAML formatter can re-indent an entire document by parsing it into a data structure and re-serializing with the desired indentation width. This is the safest way to convert, as it handles all edge cases including multi-line strings and nested structures.
Use Case
Indentation standardization is critical when teams adopt a shared YAML style. When migrating between tools (e.g., from Ansible with 4-space to Kubernetes with 2-space), bulk re-indentation ensures consistency. CI/CD pipelines can enforce indentation standards using YAML linters like yamllint with a formatter as the auto-fix step.