yaml_idiosyncrasies.rst 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  1. .. _yaml-idiosyncrasies:
  2. ===================
  3. YAML Idiosyncrasies
  4. ===================
  5. One of Salt's strengths, the use of existing serialization systems for
  6. representing SLS data, can also backfire. `YAML`_ is a general purpose system
  7. and there are a number of things that would seem to make sense in an sls
  8. file that cause YAML issues. It is wise to be aware of these issues. While
  9. reports or running into them are generally rare they can still crop up at
  10. unexpected times.
  11. .. _`YAML`: https://yaml.org/spec/1.1/
  12. Spaces vs Tabs
  13. ==============
  14. `YAML uses spaces`_, period. Do not use tabs in your SLS files! If strange
  15. errors are coming up in rendering SLS files, make sure to check that
  16. no tabs have crept in! In Vim, after enabling search highlighting
  17. with: ``:set hlsearch``, you can check with the following key sequence in
  18. normal mode(you can hit `ESC` twice to be sure): ``/``, `Ctrl-v`, `Tab`, then
  19. hit `Enter`. Also, you can convert tabs to 2 spaces by these commands in Vim:
  20. ``:set tabstop=2 expandtab`` and then ``:retab``.
  21. .. _`YAML uses spaces`: https://yaml.org/spec/1.1/#id871998
  22. Indentation
  23. ===========
  24. The suggested syntax for YAML files is to use 2 spaces for indentation,
  25. but YAML will follow whatever indentation system that the individual file
  26. uses. Indentation of two spaces works very well for SLS files given the
  27. fact that the data is uniform and not deeply nested.
  28. .. _nested-dict-indentation:
  29. Nested Dictionaries
  30. -------------------
  31. When dictionaries are nested within other data structures (particularly lists),
  32. the indentation logic sometimes changes. Examples of where this might happen
  33. include ``context`` and ``default`` options from the :mod:`file.managed
  34. <salt.states.file>` state:
  35. .. code-block:: yaml
  36. /etc/http/conf/http.conf:
  37. file:
  38. - managed
  39. - source: salt://apache/http.conf
  40. - user: root
  41. - group: root
  42. - mode: 644
  43. - template: jinja
  44. - context:
  45. custom_var: "override"
  46. - defaults:
  47. custom_var: "default value"
  48. other_var: 123
  49. Notice that while the indentation is two spaces per level, for the values under
  50. the ``context`` and ``defaults`` options there is a four-space indent. If only
  51. two spaces are used to indent, then those keys will be considered part of the
  52. same dictionary that contains the ``context`` key, and so the data will not be
  53. loaded correctly. If using a double indent is not desirable, then a
  54. deeply-nested dict can be declared with curly braces:
  55. .. code-block:: yaml
  56. /etc/http/conf/http.conf:
  57. file:
  58. - managed
  59. - source: salt://apache/http.conf
  60. - user: root
  61. - group: root
  62. - mode: 644
  63. - template: jinja
  64. - context: {
  65. custom_var: "override" }
  66. - defaults: {
  67. custom_var: "default value",
  68. other_var: 123 }
  69. Here is a more concrete example of how YAML actually handles these
  70. indentations, using the Python interpreter on the command line:
  71. .. code-block:: python
  72. >>> import yaml
  73. >>> yaml.safe_load('''mystate:
  74. ... file.managed:
  75. ... - context:
  76. ... some: var''')
  77. {'mystate': {'file.managed': [{'context': {'some': 'var'}}]}}
  78. >>> yaml.safe_load('''mystate:
  79. ... file.managed:
  80. ... - context:
  81. ... some: var''')
  82. {'mystate': {'file.managed': [{'some': 'var', 'context': None}]}}
  83. Note that in the second example, ``some`` is added as another key in the same
  84. dictionary, whereas in the first example, it's the start of a new dictionary.
  85. That's the distinction. ``context`` is a common example because it is a keyword
  86. arg for many functions, and should contain a dictionary.
  87. True/False, Yes/No, On/Off
  88. ==========================
  89. PyYAML will load these values as boolean ``True`` or ``False``. Un-capitalized
  90. versions will also be loaded as booleans (``true``, ``false``, ``yes``, ``no``,
  91. ``on``, and ``off``). This can be especially problematic when constructing
  92. Pillar data. Make sure that your Pillars which need to use the string versions
  93. of these values are enclosed in quotes. Pillars will be parsed twice by salt,
  94. so you'll need to wrap your values in multiple quotes, including double quotation
  95. marks (``" "``) and single quotation marks (``' '``). Note that spaces are included
  96. in the quotation type examples for clarity.
  97. Multiple quoting examples looks like this:
  98. .. code-block:: yaml
  99. - '"false"'
  100. - "'True'"
  101. - "'YES'"
  102. - '"No"'
  103. .. note::
  104. When using multiple quotes in this manner, they must be different. Using ``"" ""``
  105. or ``'' ''`` won't work in this case (spaces are included in examples for clarity).
  106. The '%' Sign
  107. ============
  108. The `%` symbol has a special meaning in YAML, it needs to be passed as a
  109. string literal:
  110. .. code-block:: yaml
  111. cheese:
  112. ssh_auth.present:
  113. - user: tbortels
  114. - source: salt://ssh_keys/chease.pub
  115. - config: '%h/.ssh/authorized_keys'
  116. Time Expressions
  117. ================
  118. PyYAML will load a time expression as the integer value of that, assuming
  119. ``HH:MM``. So for example, ``12:00`` is loaded by PyYAML as ``720``. An
  120. excellent explanation for why can be found here__.
  121. To keep time expressions like this from being loaded as integers, always quote
  122. them.
  123. .. note::
  124. When using a jinja ``load_yaml`` map, items must be quoted twice. For
  125. example:
  126. .. code-block:: jinja
  127. {% load_yaml as wsus_schedule %}
  128. FRI_10:
  129. time: '"23:00"'
  130. day: 6 - Every Friday
  131. SAT_10:
  132. time: '"06:00"'
  133. day: 7 - Every Saturday
  134. SAT_20:
  135. time: '"14:00"'
  136. day: 7 - Every Saturday
  137. SAT_30:
  138. time: '"22:00"'
  139. day: 7 - Every Saturday
  140. SUN_10:
  141. time: '"06:00"'
  142. day: 1 - Every Sunday
  143. {% endload %}
  144. .. __: https://stackoverflow.com/questions/23812676/pyyaml-parses-900-as-int/31007425#31007425
  145. YAML does not like "Double Short Decs"
  146. ======================================
  147. If I can find a way to make YAML accept "Double Short Decs" then I will, since
  148. I think that double short decs would be awesome. So what is a "Double Short
  149. Dec"? It is when you declare a multiple short decs in one ID. Here is a
  150. standard short dec, it works great:
  151. .. code-block:: yaml
  152. vim:
  153. pkg.installed
  154. The short dec means that there are no arguments to pass, so it is not required
  155. to add any arguments, and it can save space.
  156. YAML though, gets upset when declaring multiple short decs, for the record...
  157. THIS DOES NOT WORK:
  158. .. code-block:: yaml
  159. vim:
  160. pkg.installed
  161. user.present
  162. Similarly declaring a short dec in the same ID dec as a standard dec does not
  163. work either...
  164. ALSO DOES NOT WORK:
  165. .. code-block:: yaml
  166. fred:
  167. user.present
  168. ssh_auth.present:
  169. - name: AAAAB3NzaC...
  170. - user: fred
  171. - enc: ssh-dss
  172. - require:
  173. - user: fred
  174. The correct way is to define them like this:
  175. .. code-block:: yaml
  176. vim:
  177. pkg.installed: []
  178. user.present: []
  179. fred:
  180. user.present: []
  181. ssh_auth.present:
  182. - name: AAAAB3NzaC...
  183. - user: fred
  184. - enc: ssh-dss
  185. - require:
  186. - user: fred
  187. Alternatively, they can be defined the "old way", or with multiple
  188. "full decs":
  189. .. code-block:: yaml
  190. vim:
  191. pkg:
  192. - installed
  193. user:
  194. - present
  195. fred:
  196. user:
  197. - present
  198. ssh_auth:
  199. - present
  200. - name: AAAAB3NzaC...
  201. - user: fred
  202. - enc: ssh-dss
  203. - require:
  204. - user: fred
  205. .. _yaml_plain_ascii:
  206. YAML supports only plain ASCII
  207. ==============================
  208. According to YAML specification, only ASCII characters can be used.
  209. Within double-quotes, special characters may be represented with C-style
  210. escape sequences starting with a backslash ( \\ ).
  211. Examples:
  212. .. code-block:: yaml
  213. - micro: "\u00b5"
  214. - copyright: "\u00A9"
  215. - A: "\x41"
  216. - alpha: "\u0251"
  217. - Alef: "\u05d0"
  218. List of usable `Unicode characters`_ will help you to identify correct numbers.
  219. .. _`Unicode characters`: https://en.wikipedia.org/wiki/List_of_Unicode_characters
  220. Python can also be used to discover the Unicode number for a character:
  221. .. code-block:: python
  222. repr(u"Text with wrong characters i need to figure out")
  223. This shell command can find wrong characters in your SLS files:
  224. .. code-block:: bash
  225. find . -name '*.sls' -exec grep --color='auto' -P -n '[^\x00-\x7F]' \{} \;
  226. Alternatively you can toggle the `yaml_utf8` setting in your master configuration
  227. file. This is still an experimental setting but it should manage the right
  228. encoding conversion in salt after yaml states compilations.
  229. Underscores stripped in Integer Definitions
  230. ===========================================
  231. If a definition only includes numbers and underscores, it is parsed by YAML as
  232. an integer and all underscores are stripped. To ensure the object becomes a
  233. string, it should be surrounded by quotes. `More information here`_.
  234. .. _`More information here`: https://stackoverflow.com/questions/2723321/snakeyaml-how-to-disable-underscore-stripping-when-parsing
  235. Here's an example:
  236. .. code-block:: python
  237. >>> import yaml
  238. >>> yaml.safe_load('2013_05_10')
  239. 20130510
  240. >>> yaml.safe_load('"2013_05_10"')
  241. '2013_05_10'
  242. Automatic ``datetime`` conversion
  243. =================================
  244. If there is a value in a YAML file formatted ``2014-01-20 14:23:23`` or
  245. similar, YAML will automatically convert this to a Python ``datetime`` object.
  246. These objects are not msgpack serializable, and so may break core salt
  247. functionality. If values such as these are needed in a salt YAML file
  248. (specifically a configuration file), they should be formatted with surrounding
  249. strings to force YAML to serialize them as strings:
  250. .. code-block:: python
  251. >>> import yaml
  252. >>> yaml.safe_load('2014-01-20 14:23:23')
  253. datetime.datetime(2014, 1, 20, 14, 23, 23)
  254. >>> yaml.safe_load('"2014-01-20 14:23:23"')
  255. '2014-01-20 14:23:23'
  256. Additionally, numbers formatted like ``XXXX-XX-XX`` will also be converted (or
  257. YAML will attempt to convert them, and error out if it doesn't think the date
  258. is a real one). Thus, for example, if a minion were to have an ID of
  259. ``4017-16-20`` the minion would not start because YAML would complain that the
  260. date was out of range. The workaround is the same, surround the offending
  261. string with quotes:
  262. .. code-block:: python
  263. >>> import yaml
  264. >>> yaml.safe_load('4017-16-20')
  265. Traceback (most recent call last):
  266. File "<stdin>", line 1, in <module>
  267. File "/usr/local/lib/python2.7/site-packages/yaml/__init__.py", line 93, in safe_load
  268. return load(stream, SafeLoader)
  269. File "/usr/local/lib/python2.7/site-packages/yaml/__init__.py", line 71, in load
  270. return loader.get_single_data()
  271. File "/usr/local/lib/python2.7/site-packages/yaml/constructor.py", line 39, in get_single_data
  272. return self.construct_document(node)
  273. File "/usr/local/lib/python2.7/site-packages/yaml/constructor.py", line 43, in construct_document
  274. data = self.construct_object(node)
  275. File "/usr/local/lib/python2.7/site-packages/yaml/constructor.py", line 88, in construct_object
  276. data = constructor(self, node)
  277. File "/usr/local/lib/python2.7/site-packages/yaml/constructor.py", line 312, in construct_yaml_timestamp
  278. return datetime.date(year, month, day)
  279. ValueError: month must be in 1..12
  280. >>> yaml.safe_load('"4017-16-20"')
  281. '4017-16-20'
  282. Keys Limited to 1024 Characters
  283. ===============================
  284. Simple keys are limited by the `YAML Spec`_ to a single line, and cannot be
  285. longer that 1024 characters. PyYAML enforces these limitations (see here__),
  286. and therefore anything parsed as YAML in Salt is subject to them.
  287. .. _`YAML Spec`: https://yaml.org/spec/1.2/spec.html#id2792424
  288. .. __: https://github.com/yaml/pyyaml/blob/eb459f8/lib/yaml/scanner.py#L279-L293