YAML How many spaces per indent?

The YAML spec for v 1.2 merely says that

In YAML block styles, structure is determined by indentation. In general, indentation is defined as a zero or more space characters at the start of a line.

To maintain portability, tab characters must not be used in indentation, since different systems treat tabs differently. Note that most modern editors may be configured so that pressing the tab key results in the insertion of an appropriate number of spaces.

The amount of indentation is a presentation detail and must not be used to convey content information.

So you can set the indent depth to your preference, as long as you use spaces and not tabs. Interestingly, IntelliJ uses 2 spaces by default.


INDENTATION The suggested syntax for YAML files is to use 2 spaces for indentation, but YAML will follow whatever indentation system that the individual file uses. Indentation of two spaces works very well for SLS files given the fact that the data is uniform and not deeply nested.

NESTED DICTIONARIES When dictionaries are nested within other data structures (particularly lists), the indentation logic sometimes changes. Examples of where this might happen include context and default options from the file.managed state:

/etc/http/conf/http.conf:
file:
  - managed
  - source: salt://apache/http.conf
  - user: root
  - group: root
  - mode: 644
  - template: jinja
  - context:
      custom_var: "override"
  - defaults:
      custom_var: "default value"
      other_var: 123

Notice that while the indentation is two spaces per level, for the values under the context and defaults options there is a four-space indent. If only two spaces are used to indent, then those keys will be considered part of the same dictionary that contains the context key, and so the data will not be loaded correctly. If using a double indent is not desirable, then a deeply-nested dict can be declared with curly braces:

/etc/http/conf/http.conf:
file:
  - managed
  - source: salt://apache/http.conf
  - user: root
  - group: root
  - mode: 644
  - template: jinja
  - context: {
    custom_var: "override" }
  - defaults: {
    custom_var: "default value",
    other_var: 123 }

you can read more from this link


There is no requirement in YAML to indent any concrete number of spaces. There is also no requirement to be consistent. So for example, this is valid YAML:

a:
 b:
     - c
     -  d
     - e
f:
    "ghi"

Some rules might be of interest:

  • Flow content (i.e. everything that starts with { or [) can span multiple lines, but must be indented at least as many spaces as the surrounding current block level.
  • Block list items can (but don't need to) have the same indentation as the surrounding block level because - is considered part of the indentation:
a:    # top-level key
- b   # value of that key, which is a list
- c
c:    # next top-level key
 d    # non-list value which must be more indented