Best Practices
Here are some tips and tricks for how to write and format YAML files.
Formatting
Indentation
Tabs are forbidden as indentation.
You can freely choose the number of spaces for indentation. More than 8 probably don't make sense, and also this might be a hard limit in the next YAML version.
You can use different indentation inside of the same YAML document, as long as it is the same for one level.
The recommended number of spaces is 2.
# Two spaces top level: a: b c: d
# Different number of spaces are invalid top level: a: b c: d
# No tabs, please! top level: a: b c: d
The opinions on sequence indentation differ.
The YAML creators recommend to use "zero-indented" sequences:
a sequence: - with - three - items
Layout
Nested sequences can be formatted in a compact way:
sequence: - level one - - level two
When you have a sequence with more than one level, flow style might be more readable:
--- dice rolls: - - 2 - 5 - - 3 - 4 --- dice rolls: - [2, 5] - [3, 4]
You cannot start a sequence or another mapping on the same line as a mapping key:
key: inner: map
key: - sequence
But you can start a mapping as a sequence item on the same line:
--- sequence: - a: b c: d --- # compact sequence: - a: b c: d
File Extension
The recommended file extension is .yaml.
You will find a lot of applications that chose .yml though. Some also allow both extensions.
Plain Scalars
You do not need to quote scalars in most cases. The Quoting Chapter has detailed information about that.
If you are unsure, here are some hints. To be safe, use quotes:
- If it could be a special type, but you want a string (see Schema)
- If the scalar starts with a non-alphanumeric character
- If the scalar contains control characters
- If the scalar contains tabs
- If the scalar contains :<space>, <space>#, -<space>, :<end-of-string>
- If you are in flow style and the scalar contains one of{}[],