1
0

index.rst 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248
  1. .. _understanding-jinja:
  2. ===================
  3. Understanding Jinja
  4. ===================
  5. `Jinja`_ is the default templating language in SLS files.
  6. .. _Jinja: https://jinja.palletsprojects.com/en/2.11.x/templates/
  7. Jinja in States
  8. ===============
  9. Jinja is evaluated before YAML, which means it is evaluated before the States
  10. are run.
  11. The most basic usage of Jinja in state files is using control structures to
  12. wrap conditional or redundant state elements:
  13. .. code-block:: jinja
  14. {% if grains['os'] != 'FreeBSD' %}
  15. tcsh:
  16. pkg:
  17. - installed
  18. {% endif %}
  19. motd:
  20. file.managed:
  21. {% if grains['os'] == 'FreeBSD' %}
  22. - name: /etc/motd
  23. {% elif grains['os'] == 'Debian' %}
  24. - name: /etc/motd.tail
  25. {% endif %}
  26. - source: salt://motd
  27. In this example, the first **if** block will only be evaluated on minions that
  28. aren't running FreeBSD, and the second block changes the file name based on the
  29. *os* grain.
  30. Writing **if-else** blocks can lead to very redundant state files however. In
  31. this case, using :ref:`pillars<pillar>`, or using a previously
  32. defined variable might be easier:
  33. .. code-block:: jinja
  34. {% set motd = ['/etc/motd'] %}
  35. {% if grains['os'] == 'Debian' %}
  36. {% set motd = ['/etc/motd.tail', '/var/run/motd'] %}
  37. {% endif %}
  38. {% for motdfile in motd %}
  39. {{ motdfile }}:
  40. file.managed:
  41. - source: salt://motd
  42. {% endfor %}
  43. Using a variable set by the template, the `for loop`_ will iterate over the
  44. list of MOTD files to update, adding a state block for each file.
  45. The filter_by function can also be used to set variables based on grains:
  46. .. code-block:: jinja
  47. {% set auditd = salt['grains.filter_by']({
  48. 'RedHat': { 'package': 'audit' },
  49. 'Debian': { 'package': 'auditd' },
  50. }) %}
  51. .. _`for loop`: https://jinja.palletsprojects.com/en/2.11.x/templates/#for
  52. Include and Import
  53. ==================
  54. Includes and imports_ can be used to share common, reusable state configuration
  55. between state files and between files.
  56. .. code-block:: jinja
  57. {% from 'lib.sls' import test %}
  58. This would import the ``test`` template variable or macro, not the ``test``
  59. state element, from the file ``lib.sls``. In the case that the included file
  60. performs checks against grains, or something else that requires context, passing
  61. the context into the included file is required:
  62. .. code-block:: jinja
  63. {% from 'lib.sls' import test with context %}
  64. Includes must use full paths, like so:
  65. .. code-block:: jinja
  66. :caption: spam/eggs.jinja
  67. {% include 'spam/foobar.jinja' %}
  68. Including Context During Include/Import
  69. ---------------------------------------
  70. By adding ``with context`` to the include/import directive, the
  71. current context can be passed to an included/imported template.
  72. .. code-block:: jinja
  73. {% import 'openssl/vars.sls' as ssl with context %}
  74. .. _imports: https://jinja.palletsprojects.com/en/2.11.x/templates/#import
  75. Macros
  76. ======
  77. Macros_ are helpful for eliminating redundant code. Macros are most useful as
  78. mini-templates to repeat blocks of strings with a few parameterized variables.
  79. Be aware that stripping whitespace from the template block, as well as
  80. contained blocks, may be necessary to emulate a variable return from the macro.
  81. .. code-block:: jinja
  82. # init.sls
  83. {% from 'lib.sls' import pythonpkg with context %}
  84. python-virtualenv:
  85. pkg.installed:
  86. - name: {{ pythonpkg('virtualenv') }}
  87. python-fabric:
  88. pkg.installed:
  89. - name: {{ pythonpkg('fabric') }}
  90. .. code-block:: jinja
  91. # lib.sls
  92. {% macro pythonpkg(pkg) -%}
  93. {%- if grains['os'] == 'FreeBSD' -%}
  94. py27-{{ pkg }}
  95. {%- elif grains['os'] == 'Debian' -%}
  96. python-{{ pkg }}
  97. {%- endif -%}
  98. {%- endmacro %}
  99. This would define a macro_ that would return a string of the full package name,
  100. depending on the packaging system's naming convention. The whitespace of the
  101. macro was eliminated, so that the macro would return a string without line
  102. breaks, using `whitespace control`_.
  103. Template Inheritance
  104. ====================
  105. `Template inheritance`_ works fine from state files and files. The search path
  106. starts at the root of the state tree or pillar.
  107. .. _`Template inheritance`: https://jinja.palletsprojects.com/en/2.11.x/templates/#template-inheritance
  108. .. _`Macros`: https://jinja.palletsprojects.com/en/2.11.x/templates/#macros
  109. .. _`macro`: https://jinja.palletsprojects.com/en/2.11.x/templates/#macros
  110. .. _`Whitespace control`: https://jinja.palletsprojects.com/en/2.11.x/templates/#whitespace-control
  111. Errors
  112. ======
  113. Saltstack allows raising custom errors using the ``raise`` jinja function.
  114. .. code-block:: jinja
  115. {{ raise('Custom Error') }}
  116. When rendering the template containing the above statement, a ``TemplateError``
  117. exception is raised, causing the rendering to fail with the following message:
  118. .. code-block:: text
  119. TemplateError: Custom Error
  120. Filters
  121. =======
  122. Saltstack extends `builtin filters`_ with these custom filters:
  123. .. jinja_ref:: strftime
  124. ``strftime``
  125. ------------
  126. Converts any time related object into a time based string. It requires valid
  127. strftime directives. An exhaustive list can be found :ref:`here
  128. <python:strftime-strptime-behavior>` in the Python documentation.
  129. .. code-block:: jinja
  130. {% set curtime = None | strftime() %}
  131. Fuzzy dates require the `timelib`_ Python module is installed.
  132. .. code-block:: jinja
  133. {{ "2002/12/25"|strftime("%y") }}
  134. {{ "1040814000"|strftime("%Y-%m-%d") }}
  135. {{ datetime|strftime("%u") }}
  136. {{ "tomorrow"|strftime }}
  137. .. jinja_ref:: sequence
  138. ``sequence``
  139. ------------
  140. Ensure that parsed data is a sequence.
  141. .. jinja_ref:: yaml_encode
  142. ``yaml_encode``
  143. ---------------
  144. Serializes a single object into a YAML scalar with any necessary
  145. handling for escaping special characters. This will work for any
  146. scalar YAML data type: ints, floats, timestamps, booleans, strings,
  147. unicode. It will *not* work for multi-objects such as sequences or
  148. maps.
  149. .. code-block:: jinja
  150. {%- set bar = 7 %}
  151. {%- set baz = none %}
  152. {%- set zip = true %}
  153. {%- set zap = 'The word of the day is "salty"' %}
  154. {%- load_yaml as foo %}
  155. bar: {{ bar|yaml_encode }}
  156. baz: {{ baz|yaml_encode }}
  157. zip: {{ zip|yaml_encode }}
  158. zap: {{ zap|yaml_encode }}
  159. {%- endload %}
  160. In the above case ``{{ bar }}`` and ``{{ foo.bar }}`` should be
  161. identical and ``{{ baz }}`` and ``{{ foo.baz }}`` should be
  162. identical.
  163. .. jinja_ref:: yaml_dquote
  164. ``yaml_dquote``
  165. ---------------
  166. Serializes a string into a properly-escaped YAML double-quoted
  167. string. This is useful when the contents of a string are unknown
  168. and may contain quotes or unicode that needs to be preserved. The
  169. resulting string will be emitted with opening and closing double
  170. quotes.
  171. .. code-block:: jinja
  172. {%- set bar = '"The quick brown fox . . ."' %}
  173. {%- set baz = 'The word of the day is "salty".' %}
  174. {%- load_yaml as foo %}
  175. bar: {{ bar|yaml_dquote }}
  176. baz: {{ baz|yaml_dquote }}
  177. {%- endload %}
  178. In the above case ``{{ bar }}`` and ``{{ foo.bar }}`` should be
  179. identical and ``{{ baz }}`` and ``{{ foo.baz }}`` should be
  180. identical. If variable contents are not guaranteed to be a string
  181. then it is better to use ``yaml_encode`` which handles all YAML
  182. scalar types.
  183. .. jinja_ref:: yaml_squote
  184. ``yaml_squote``
  185. ---------------
  186. Similar to the ``yaml_dquote`` filter but with single quotes. Note
  187. that YAML only allows special escapes inside double quotes so
  188. ``yaml_squote`` is not nearly as useful (viz. you likely want to
  189. use ``yaml_encode`` or ``yaml_dquote``).
  190. .. jinja_ref:: to_bool
  191. ``to_bool``
  192. -----------
  193. .. versionadded:: 2017.7.0
  194. Returns the logical value of an element.
  195. Example:
  196. .. code-block:: jinja
  197. {{ 'yes' | to_bool }}
  198. {{ 'true' | to_bool }}
  199. {{ 1 | to_bool }}
  200. {{ 'no' | to_bool }}
  201. Will be rendered as:
  202. .. code-block:: python
  203. True
  204. True
  205. True
  206. False
  207. .. jinja_ref:: exactly_n_true
  208. ``exactly_n_true``
  209. ------------------
  210. .. versionadded:: 2017.7.0
  211. Tests that exactly N items in an iterable are "truthy" (neither None, False, nor 0).
  212. Example:
  213. .. code-block:: jinja
  214. {{ ['yes', 0, False, 'True'] | exactly_n_true(2) }}
  215. Returns:
  216. .. code-block:: python
  217. True
  218. .. jinja_ref:: exactly_one_true
  219. ``exactly_one_true``
  220. --------------------
  221. .. versionadded:: 2017.7.0
  222. Tests that exactly one item in an iterable is "truthy" (neither None, False, nor 0).
  223. Example:
  224. .. code-block:: jinja
  225. {{ ['yes', False, 0, None] | exactly_one_true }}
  226. Returns:
  227. .. code-block:: python
  228. True
  229. .. jinja_ref:: quote
  230. ``quote``
  231. ---------
  232. .. versionadded:: 2017.7.0
  233. This text will be wrapped in quotes.
  234. .. jinja_ref:: regex_search
  235. ``regex_search``
  236. ----------------
  237. .. versionadded:: 2017.7.0
  238. Scan through string looking for a location where this regular expression
  239. produces a match. Returns ``None`` in case there were no matches found
  240. Example:
  241. .. code-block:: jinja
  242. {{ 'abcdefabcdef' | regex_search('BC(.*)', ignorecase=True) }}
  243. Returns:
  244. .. code-block:: python
  245. ("defabcdef",)
  246. .. jinja_ref:: regex_match
  247. ``regex_match``
  248. ---------------
  249. .. versionadded:: 2017.7.0
  250. If zero or more characters at the beginning of string match this regular
  251. expression, otherwise returns ``None``.
  252. Example:
  253. .. code-block:: jinja
  254. {{ 'abcdefabcdef' | regex_match('BC(.*)', ignorecase=True) }}
  255. Returns:
  256. .. code-block:: text
  257. None
  258. .. jinja_ref:: regex_replace
  259. ``regex_replace``
  260. -----------------
  261. .. versionadded:: 2017.7.0
  262. Searches for a pattern and replaces with a sequence of characters.
  263. Example:
  264. .. code-block:: jinja
  265. {% set my_text = 'yes, this is a TEST' %}
  266. {{ my_text | regex_replace(' ([a-z])', '__\\1', ignorecase=True) }}
  267. Returns:
  268. .. code-block:: text
  269. yes,__this__is__a__TEST
  270. .. jinja_ref:: uuid
  271. ``uuid``
  272. --------
  273. .. versionadded:: 2017.7.0
  274. Return a UUID.
  275. Example:
  276. .. code-block:: jinja
  277. {{ 'random' | uuid }}
  278. Returns:
  279. .. code-block:: text
  280. 3652b285-26ad-588e-a5dc-c2ee65edc804
  281. .. jinja_ref:: is_list
  282. ``is_list``
  283. -----------
  284. .. versionadded:: 2017.7.0
  285. Return if an object is list.
  286. Example:
  287. .. code-block:: jinja
  288. {{ [1, 2, 3] | is_list }}
  289. Returns:
  290. .. code-block:: python
  291. True
  292. .. jinja_ref:: is_iter
  293. ``is_iter``
  294. -----------
  295. .. versionadded:: 2017.7.0
  296. Return if an object is iterable.
  297. Example:
  298. .. code-block:: jinja
  299. {{ [1, 2, 3] | is_iter }}
  300. Returns:
  301. .. code-block:: python
  302. True
  303. .. jinja_ref:: min
  304. ``min``
  305. -------
  306. .. versionadded:: 2017.7.0
  307. Return the minimum value from a list.
  308. Example:
  309. .. code-block:: jinja
  310. {{ [1, 2, 3] | min }}
  311. Returns:
  312. .. code-block:: text
  313. 1
  314. .. jinja_ref:: max
  315. ``max``
  316. -------
  317. .. versionadded:: 2017.7.0
  318. Returns the maximum value from a list.
  319. Example:
  320. .. code-block:: jinja
  321. {{ [1, 2, 3] | max }}
  322. Returns:
  323. .. code-block:: text
  324. 3
  325. .. jinja_ref:: avg
  326. ``avg``
  327. -------
  328. .. versionadded:: 2017.7.0
  329. Returns the average value of the elements of a list
  330. Example:
  331. .. code-block:: jinja
  332. {{ [1, 2, 3] | avg }}
  333. Returns:
  334. .. code-block:: text
  335. 2
  336. .. jinja_ref:: union
  337. ``union``
  338. ---------
  339. .. versionadded:: 2017.7.0
  340. Return the union of two lists.
  341. Example:
  342. .. code-block:: jinja
  343. {{ [1, 2, 3] | union([2, 3, 4]) | join(', ') }}
  344. Returns:
  345. .. code-block:: text
  346. 1, 2, 3, 4
  347. .. jinja_ref:: intersect
  348. ``intersect``
  349. -------------
  350. .. versionadded:: 2017.7.0
  351. Return the intersection of two lists.
  352. Example:
  353. .. code-block:: jinja
  354. {{ [1, 2, 3] | intersect([2, 3, 4]) | join(', ') }}
  355. Returns:
  356. .. code-block:: text
  357. 2, 3
  358. .. jinja_ref:: difference
  359. ``difference``
  360. --------------
  361. .. versionadded:: 2017.7.0
  362. Return the difference of two lists.
  363. Example:
  364. .. code-block:: jinja
  365. {{ [1, 2, 3] | difference([2, 3, 4]) | join(', ') }}
  366. Returns:
  367. .. code-block:: text
  368. 1
  369. .. jinja_ref:: symmetric_difference
  370. ``symmetric_difference``
  371. ------------------------
  372. .. versionadded:: 2017.7.0
  373. Return the symmetric difference of two lists.
  374. Example:
  375. .. code-block:: jinja
  376. {{ [1, 2, 3] | symmetric_difference([2, 3, 4]) | join(', ') }}
  377. Returns:
  378. .. code-block:: text
  379. 1, 4
  380. .. jinja_ref:: method_call
  381. ``method_call``
  382. ---------------
  383. .. versionadded:: 3001
  384. Returns a result of object's method call.
  385. Example #1:
  386. .. code-block:: jinja
  387. {{ [1, 2, 1, 3, 4] | method_call('index', 1, 1, 3) }}
  388. Returns:
  389. .. code-block:: text
  390. 2
  391. This filter can be used with the `map filter`_ to apply object methods without
  392. using loop constructs or temporary variables.
  393. Example #2:
  394. .. code-block:: jinja
  395. {% set host_list = ['web01.example.com', 'db01.example.com'] %}
  396. {% set host_list_split = [] %}
  397. {% for item in host_list %}
  398. {% do host_list_split.append(item.split('.', 1)) %}
  399. {% endfor %}
  400. {{ host_list_split }}
  401. Example #3:
  402. .. code-block:: jinja
  403. {{ host_list|map('method_call', 'split', '.', 1)|list }}
  404. Return of examples #2 and #3:
  405. .. code-block:: text
  406. [[web01, example.com], [db01, example.com]]
  407. .. _`map filter`: https://jinja.palletsprojects.com/en/2.11.x/templates/#map
  408. .. jinja_ref:: is_sorted
  409. ``is_sorted``
  410. -------------
  411. .. versionadded:: 2017.7.0
  412. Return ``True`` if an iterable object is already sorted.
  413. Example:
  414. .. code-block:: jinja
  415. {{ [1, 2, 3] | is_sorted }}
  416. Returns:
  417. .. code-block:: python
  418. True
  419. .. jinja_ref:: compare_lists
  420. ``compare_lists``
  421. -----------------
  422. .. versionadded:: 2017.7.0
  423. Compare two lists and return a dictionary with the changes.
  424. Example:
  425. .. code-block:: jinja
  426. {{ [1, 2, 3] | compare_lists([1, 2, 4]) }}
  427. Returns:
  428. .. code-block:: python
  429. {"new": [4], "old": [3]}
  430. .. jinja_ref:: compare_dicts
  431. ``compare_dicts``
  432. -----------------
  433. .. versionadded:: 2017.7.0
  434. Compare two dictionaries and return a dictionary with the changes.
  435. Example:
  436. .. code-block:: jinja
  437. {{ {'a': 'b'} | compare_dicts({'a': 'c'}) }}
  438. Returns:
  439. .. code-block:: python
  440. {"a": {"new": "c", "old": "b"}}
  441. .. jinja_ref:: is_hex
  442. ``is_hex``
  443. ----------
  444. .. versionadded:: 2017.7.0
  445. Return ``True`` if the value is hexadecimal.
  446. Example:
  447. .. code-block:: jinja
  448. {{ '0xabcd' | is_hex }}
  449. {{ 'xyzt' | is_hex }}
  450. Returns:
  451. .. code-block:: python
  452. True
  453. False
  454. .. jinja_ref:: contains_whitespace
  455. ``contains_whitespace``
  456. -----------------------
  457. .. versionadded:: 2017.7.0
  458. Return ``True`` if a text contains whitespaces.
  459. Example:
  460. .. code-block:: jinja
  461. {{ 'abcd' | contains_whitespace }}
  462. {{ 'ab cd' | contains_whitespace }}
  463. Returns:
  464. .. code-block:: python
  465. False
  466. True
  467. .. jinja_ref:: substring_in_list
  468. ``substring_in_list``
  469. ---------------------
  470. .. versionadded:: 2017.7.0
  471. Return ``True`` if a substring is found in a list of string values.
  472. Example:
  473. .. code-block:: jinja
  474. {{ 'abcd' | substring_in_list(['this', 'is', 'an abcd example']) }}
  475. Returns:
  476. .. code-block:: python
  477. True
  478. .. jinja_ref:: check_whitelist_blacklist
  479. ``check_whitelist_blacklist``
  480. -----------------------------
  481. .. versionadded:: 2017.7.0
  482. Check a whitelist and/or blacklist to see if the value matches it.
  483. This filter can be used with either a whitelist or a blacklist individually,
  484. or a whitelist and a blacklist can be passed simultaneously.
  485. If whitelist is used alone, value membership is checked against the
  486. whitelist only. If the value is found, the function returns ``True``.
  487. Otherwise, it returns ``False``.
  488. If blacklist is used alone, value membership is checked against the
  489. blacklist only. If the value is found, the function returns ``False``.
  490. Otherwise, it returns ``True``.
  491. If both a whitelist and a blacklist are provided, value membership in the
  492. blacklist will be examined first. If the value is not found in the blacklist,
  493. then the whitelist is checked. If the value isn't found in the whitelist,
  494. the function returns ``False``.
  495. Whitelist Example:
  496. .. code-block:: jinja
  497. {{ 5 | check_whitelist_blacklist(whitelist=[5, 6, 7]) }}
  498. Returns:
  499. .. code-block:: python
  500. True
  501. Blacklist Example:
  502. .. code-block:: jinja
  503. {{ 5 | check_whitelist_blacklist(blacklist=[5, 6, 7]) }}
  504. .. code-block:: python
  505. False
  506. .. jinja_ref:: date_format
  507. ``date_format``
  508. ---------------
  509. .. versionadded:: 2017.7.0
  510. Converts unix timestamp into human-readable string.
  511. Example:
  512. .. code-block:: jinja
  513. {{ 1457456400 | date_format }}
  514. {{ 1457456400 | date_format('%d.%m.%Y %H:%M') }}
  515. Returns:
  516. .. code-block:: text
  517. 2017-03-08
  518. 08.03.2017 17:00
  519. .. jinja_ref:: to_num
  520. ``to_num``
  521. ----------
  522. .. versionadded:: 2017.7.0
  523. .. versionadded:: 2018.3.0
  524. Renamed from ``str_to_num`` to ``to_num``.
  525. Converts a string to its numerical value.
  526. Example:
  527. .. code-block:: jinja
  528. {{ '5' | to_num }}
  529. Returns:
  530. .. code-block:: python
  531. 5
  532. .. jinja_ref:: to_bytes
  533. ``to_bytes``
  534. ------------
  535. .. versionadded:: 2017.7.0
  536. Converts string-type object to bytes.
  537. Example:
  538. .. code-block:: jinja
  539. {{ 'wall of text' | to_bytes }}
  540. .. note::
  541. This option may have adverse effects when using the default renderer,
  542. ``jinja|yaml``. This is due to the fact that YAML requires proper handling
  543. in regard to special characters. Please see the section on :ref:`YAML ASCII
  544. support <yaml_plain_ascii>` in the :ref:`YAML Idiosyncracies
  545. <yaml-idiosyncrasies>` documentation for more information.
  546. .. jinja_ref:: json_decode_list
  547. .. jinja_ref:: json_encode_list
  548. ``json_encode_list``
  549. --------------------
  550. .. versionadded:: 2017.7.0
  551. .. versionadded:: 2018.3.0
  552. Renamed from ``json_decode_list`` to ``json_encode_list``. When you encode
  553. something you get bytes, and when you decode, you get your locale's
  554. encoding (usually a ``unicode`` type). This filter was incorrectly-named
  555. when it was added. ``json_decode_list`` will be supported until the Aluminium
  556. release.
  557. .. deprecated:: 2018.3.3,2019.2.0
  558. The :jinja_ref:`tojson` filter accomplishes what this filter was designed
  559. to do, making this filter redundant.
  560. Recursively encodes all string elements of the list to bytes.
  561. Example:
  562. .. code-block:: jinja
  563. {{ [1, 2, 3] | json_encode_list }}
  564. Returns:
  565. .. code-block:: python
  566. [1, 2, 3]
  567. .. jinja_ref:: json_decode_dict
  568. .. jinja_ref:: json_encode_dict
  569. ``json_encode_dict``
  570. --------------------
  571. .. versionadded:: 2017.7.0
  572. .. versionadded:: 2018.3.0
  573. Renamed from ``json_decode_dict`` to ``json_encode_dict``. When you encode
  574. something you get bytes, and when you decode, you get your locale's
  575. encoding (usually a ``unicode`` type). This filter was incorrectly-named
  576. when it was added. ``json_decode_dict`` will be supported until the Aluminium
  577. release.
  578. .. deprecated:: 2018.3.3,2019.2.0
  579. The :jinja_ref:`tojson` filter accomplishes what this filter was designed
  580. to do, making this filter redundant.
  581. Recursively encodes all string items in the dictionary to bytes.
  582. Example:
  583. Assuming that ``pillar['foo']`` contains ``{u'a': u'\u0414'}``, and your locale
  584. is ``en_US.UTF-8``:
  585. .. code-block:: jinja
  586. {{ pillar['foo'] | json_encode_dict }}
  587. Returns:
  588. .. code-block:: python
  589. {"a": "\xd0\x94"}
  590. .. jinja_ref:: tojson
  591. ``tojson``
  592. ----------
  593. .. versionadded:: 2018.3.3,2019.2.0
  594. Dumps a data structure to JSON.
  595. This filter was added to provide this functionality to hosts which have a
  596. Jinja release older than version 2.9 installed. If Jinja 2.9 or newer is
  597. installed, then the upstream version of the filter will be used. See the
  598. `upstream docs`__ for more information.
  599. .. __: https://jinja.palletsprojects.com/en/2.11.x/templates/#tojson
  600. .. jinja_ref:: random_hash
  601. ``random_hash``
  602. ---------------
  603. .. versionadded:: 2017.7.0
  604. .. versionadded:: 2018.3.0
  605. Renamed from ``rand_str`` to ``random_hash`` to more accurately describe
  606. what the filter does. ``rand_str`` will be supported to ensure backwards
  607. compatibility but please use the preferred ``random_hash``.
  608. Generates a random number between 1 and the number passed to the filter, and
  609. then hashes it. The default hash type is the one specified by the minion's
  610. :conf_minion:`hash_type` config option, but an alternate hash type can be
  611. passed to the filter as an argument.
  612. Example:
  613. .. code-block:: jinja
  614. {% set num_range = 99999999 %}
  615. {{ num_range | random_hash }}
  616. {{ num_range | random_hash('sha512') }}
  617. Returns:
  618. .. code-block:: text
  619. 43ec517d68b6edd3015b3edc9a11367b
  620. d94a45acd81f8e3107d237dbc0d5d195f6a52a0d188bc0284c0763ece1eac9f9496fb6a531a296074c87b3540398dace1222b42e150e67c9301383fde3d66ae5
  621. .. jinja_ref:: set_dict_key_value
  622. ``set_dict_key_value``
  623. ----------------------
  624. .. versionadded:: 3000
  625. Allows you to set a value in a nested dictionary without having to worry if all the nested keys actually exist.
  626. Missing keys will be automatically created if they do not exist.
  627. The default delimiter for the keys is ':', however, with the `delimiter`-parameter, a different delimiter can be specified.
  628. Examples:
  629. .. code-block:: jinja
  630. Example 1:
  631. {%- set foo = {} %}
  632. {{ foo | set_dict_key_value('bar:baz', 42) }}
  633. Example 2:
  634. {{ {} | set_dict_key_value('bar.baz.qux', 42, delimiter='.') }}
  635. Returns:
  636. .. code-block:: text
  637. Example 1:
  638. {'bar': {'baz': 42}}
  639. Example 2:
  640. {'bar': {'baz': {'qux': 42}}}
  641. .. jinja_ref:: append_dict_key_value
  642. ``append_dict_key_value``
  643. -------------------------
  644. .. versionadded:: 3000
  645. Allows you to append to a list nested (deep) in a dictionary without having to worry if all the nested keys (or the list itself) actually exist.
  646. Missing keys will automatically be created if they do not exist.
  647. The default delimiter for the keys is ':', however, with the `delimiter`-parameter, a different delimiter can be specified.
  648. Examples:
  649. .. code-block:: jinja
  650. Example 1:
  651. {%- set foo = {'bar': {'baz': [1, 2]}} %}
  652. {{ foo | append_dict_key_value('bar:baz', 42) }}
  653. Example 2:
  654. {%- set foo = {} %}
  655. {{ foo | append_dict_key_value('bar:baz:qux', 42) }}
  656. Returns:
  657. .. code-block:: text
  658. Example 1:
  659. {'bar': {'baz': [1, 2, 42]}}
  660. Example 2:
  661. {'bar': {'baz': {'qux': [42]}}}
  662. .. jinja_ref:: extend_dict_key_value
  663. ``extend_dict_key_value``
  664. -------------------------
  665. .. versionadded:: 3000
  666. Allows you to extend a list nested (deep) in a dictionary without having to worry if all the nested keys (or the list itself) actually exist.
  667. Missing keys will automatically be created if they do not exist.
  668. The default delimiter for the keys is ':', however, with the `delimiter`-parameter, a different delimiter can be specified.
  669. Examples:
  670. .. code-block:: jinja
  671. Example 1:
  672. {%- set foo = {'bar': {'baz': [1, 2]}} %}
  673. {{ foo | extend_dict_key_value('bar:baz', [42, 42]) }}
  674. Example 2:
  675. {{ {} | extend_dict_key_value('bar:baz:qux', [42]) }}
  676. Returns:
  677. .. code-block:: text
  678. Example 1:
  679. {'bar': {'baz': [1, 2, 42, 42]}}
  680. Example 2:
  681. {'bar': {'baz': {'qux': [42]}}}
  682. .. jinja_ref:: update_dict_key_value
  683. ``update_dict_key_value``
  684. -------------------------
  685. .. versionadded:: 3000
  686. Allows you to update a dictionary nested (deep) in another dictionary without having to worry if all the nested keys actually exist.
  687. Missing keys will automatically be created if they do not exist.
  688. The default delimiter for the keys is ':', however, with the `delimiter`-parameter, a different delimiter can be specified.
  689. Examples:
  690. .. code-block:: jinja
  691. Example 1:
  692. {%- set foo = {'bar': {'baz': {'qux': 1}}} %}
  693. {{ foo | update_dict_key_value('bar:baz', {'quux': 3}) }}
  694. Example 2:
  695. {{ {} | update_dict_key_value('bar:baz:qux', {'quux': 3}) }}
  696. .. code-block:: text
  697. Example 1:
  698. {'bar': {'baz': {'qux': 1, 'quux': 3}}}
  699. Example 2:
  700. {'bar': {'baz': {'qux': {'quux': 3}}}}
  701. .. jinja_ref:: md5
  702. ``md5``
  703. -------
  704. .. versionadded:: 2017.7.0
  705. Return the md5 digest of a string.
  706. Example:
  707. .. code-block:: jinja
  708. {{ 'random' | md5 }}
  709. Returns:
  710. .. code-block:: text
  711. 7ddf32e17a6ac5ce04a8ecbf782ca509
  712. .. jinja_ref:: sha256
  713. ``sha256``
  714. ----------
  715. .. versionadded:: 2017.7.0
  716. Return the sha256 digest of a string.
  717. Example:
  718. .. code-block:: jinja
  719. {{ 'random' | sha256 }}
  720. Returns:
  721. .. code-block:: text
  722. a441b15fe9a3cf56661190a0b93b9dec7d04127288cc87250967cf3b52894d11
  723. .. jinja_ref:: sha512
  724. ``sha512``
  725. ----------
  726. .. versionadded:: 2017.7.0
  727. Return the sha512 digest of a string.
  728. Example:
  729. .. code-block:: jinja
  730. {{ 'random' | sha512 }}
  731. Returns:
  732. .. code-block:: text
  733. 811a90e1c8e86c7b4c0eef5b2c0bf0ec1b19c4b1b5a242e6455be93787cb473cb7bc9b0fdeb960d00d5c6881c2094dd63c5c900ce9057255e2a4e271fc25fef1
  734. .. jinja_ref:: base64_encode
  735. ``base64_encode``
  736. -----------------
  737. .. versionadded:: 2017.7.0
  738. Encode a string as base64.
  739. Example:
  740. .. code-block:: jinja
  741. {{ 'random' | base64_encode }}
  742. Returns:
  743. .. code-block:: text
  744. cmFuZG9t
  745. .. jinja_ref:: base64_decode
  746. ``base64_decode``
  747. -----------------
  748. .. versionadded:: 2017.7.0
  749. Decode a base64-encoded string.
  750. .. code-block:: jinja
  751. {{ 'Z2V0IHNhbHRlZA==' | base64_decode }}
  752. Returns:
  753. .. code-block:: text
  754. get salted
  755. .. jinja_ref:: hmac
  756. ``hmac``
  757. --------
  758. .. versionadded:: 2017.7.0
  759. Verify a challenging hmac signature against a string / shared-secret. Returns
  760. a boolean value.
  761. Example:
  762. .. code-block:: jinja
  763. {{ 'get salted' | hmac('shared secret', 'eBWf9bstXg+NiP5AOwppB5HMvZiYMPzEM9W5YMm/AmQ=') }}
  764. Returns:
  765. .. code-block:: python
  766. True
  767. .. jinja_ref:: http_query
  768. ``http_query``
  769. --------------
  770. .. versionadded:: 2017.7.0
  771. Return the HTTP reply object from a URL.
  772. Example:
  773. .. code-block:: jinja
  774. {{ 'http://jsonplaceholder.typicode.com/posts/1' | http_query }}
  775. Returns:
  776. .. code-block:: python
  777. {
  778. 'body': '{
  779. "userId": 1,
  780. "id": 1,
  781. "title": "sunt aut facere repellat provident occaecati excepturi option reprehenderit",
  782. "body": "quia et suscipit\\nsuscipit recusandae consequuntur expedita et cum\\nreprehenderit molestiae ut ut quas totam\\nnostrum rerum est autem sunt rem eveniet architecto"
  783. }'
  784. }
  785. .. jinja_ref:: traverse
  786. ``traverse``
  787. ------------
  788. .. versionadded:: 2018.3.3
  789. Traverse a dict or list using a colon-delimited target string.
  790. The target 'foo:bar:0' will return data['foo']['bar'][0] if this value exists,
  791. and will otherwise return the provided default value.
  792. Example:
  793. .. code-block:: jinja
  794. {{ {'a1': {'b1': {'c1': 'foo'}}, 'a2': 'bar'} | traverse('a1:b1', 'default') }}
  795. Returns:
  796. .. code-block:: python
  797. {"c1": "foo"}
  798. .. code-block:: jinja
  799. {{ {'a1': {'b1': {'c1': 'foo'}}, 'a2': 'bar'} | traverse('a2:b2', 'default') }}
  800. Returns:
  801. .. code-block:: python
  802. "default"
  803. .. jinja_ref:: json_query
  804. ``json_query``
  805. --------------
  806. .. versionadded:: 3000
  807. A port of Ansible ``json_query`` Jinja filter to make queries against JSON data using `JMESPath language`_.
  808. Could be used to filter ``pillar`` data, ``yaml`` maps, and together with :jinja_ref:`http_query`.
  809. Depends on the `jmespath`_ Python module.
  810. Examples:
  811. .. code-block:: jinja
  812. Example 1: {{ [1, 2, 3, 4, [5, 6]] | json_query('[]') }}
  813. Example 2: {{
  814. {"machines": [
  815. {"name": "a", "state": "running"},
  816. {"name": "b", "state": "stopped"},
  817. {"name": "c", "state": "running"}
  818. ]} | json_query("machines[?state=='running'].name") }}
  819. Example 3: {{
  820. {"services": [
  821. {"name": "http", "host": "1.2.3.4", "port": 80},
  822. {"name": "smtp", "host": "1.2.3.5", "port": 25},
  823. {"name": "ssh", "host": "1.2.3.6", "port": 22},
  824. ]} | json_query("services[].port") }}
  825. Returns:
  826. .. code-block:: text
  827. Example 1: [1, 2, 3, 4, 5, 6]
  828. Example 2: ['a', 'c']
  829. Example 3: [80, 25, 22]
  830. .. _`builtin filters`: https://jinja.palletsprojects.com/en/2.11.x/templates/#builtin-filters
  831. .. _`timelib`: https://github.com/pediapress/timelib/
  832. .. _`JMESPath language`: https://jmespath.org/
  833. .. _`jmespath`: https://github.com/jmespath/jmespath.py
  834. .. jinja_ref:: to_snake_case
  835. ``to_snake_case``
  836. -----------------
  837. .. versionadded:: 3000
  838. Converts a string from camelCase (or CamelCase) to snake_case.
  839. .. code-block:: jinja
  840. Example: {{ camelsWillLoveThis | to_snake_case }}
  841. Returns:
  842. .. code-block:: text
  843. Example: camels_will_love_this
  844. .. jinja_ref:: to_camelcase
  845. ``to_camelcase``
  846. ----------------
  847. .. versionadded:: 3000
  848. Converts a string from snake_case to camelCase (or UpperCamelCase if so indicated).
  849. .. code-block:: jinja
  850. Example 1: {{ snake_case_for_the_win | to_camelcase }}
  851. Example 2: {{ snake_case_for_the_win | to_camelcase(uppercamel=True) }}
  852. Returns:
  853. .. code-block:: text
  854. Example 1: snakeCaseForTheWin
  855. Example 2: SnakeCaseForTheWin
  856. Networking Filters
  857. ------------------
  858. The following networking-related filters are supported:
  859. .. jinja_ref:: is_ip
  860. ``is_ip``
  861. ---------
  862. .. versionadded:: 2017.7.0
  863. Return if a string is a valid IP Address.
  864. .. code-block:: jinja
  865. {{ '192.168.0.1' | is_ip }}
  866. Additionally accepts the following options:
  867. - global
  868. - link-local
  869. - loopback
  870. - multicast
  871. - private
  872. - public
  873. - reserved
  874. - site-local
  875. - unspecified
  876. Example - test if a string is a valid loopback IP address.
  877. .. code-block:: jinja
  878. {{ '192.168.0.1' | is_ip(options='loopback') }}
  879. .. jinja_ref:: is_ipv4
  880. ``is_ipv4``
  881. -----------
  882. .. versionadded:: 2017.7.0
  883. Returns if a string is a valid IPv4 address. Supports the same options
  884. as ``is_ip``.
  885. .. code-block:: jinja
  886. {{ '192.168.0.1' | is_ipv4 }}
  887. .. jinja_ref:: is_ipv6
  888. ``is_ipv6``
  889. -----------
  890. .. versionadded:: 2017.7.0
  891. Returns if a string is a valid IPv6 address. Supports the same options
  892. as ``is_ip``.
  893. .. code-block:: jinja
  894. {{ 'fe80::' | is_ipv6 }}
  895. .. jinja_ref:: ipaddr
  896. ``ipaddr``
  897. ----------
  898. .. versionadded:: 2017.7.0
  899. From a list, returns only valid IP entries. Supports the same options
  900. as ``is_ip``. The list can contains also IP interfaces/networks.
  901. Example:
  902. .. code-block:: jinja
  903. {{ ['192.168.0.1', 'foo', 'bar', 'fe80::'] | ipaddr }}
  904. Returns:
  905. .. code-block:: python
  906. ["192.168.0.1", "fe80::"]
  907. .. jinja_ref:: ipv4
  908. ``ipv4``
  909. --------
  910. .. versionadded:: 2017.7.0
  911. From a list, returns only valid IPv4 entries. Supports the same options
  912. as ``is_ip``. The list can contains also IP interfaces/networks.
  913. Example:
  914. .. code-block:: jinja
  915. {{ ['192.168.0.1', 'foo', 'bar', 'fe80::'] | ipv4 }}
  916. Returns:
  917. .. code-block:: python
  918. ["192.168.0.1"]
  919. .. jinja_ref:: ipv6
  920. ``ipv6``
  921. --------
  922. .. versionadded:: 2017.7.0
  923. From a list, returns only valid IPv6 entries. Supports the same options
  924. as ``is_ip``. The list can contains also IP interfaces/networks.
  925. Example:
  926. .. code-block:: jinja
  927. {{ ['192.168.0.1', 'foo', 'bar', 'fe80::'] | ipv6 }}
  928. Returns:
  929. .. code-block:: python
  930. ["fe80::"]
  931. .. jinja_ref:: network_hosts
  932. ``network_hosts``
  933. -----------------
  934. .. versionadded:: 2017.7.0
  935. Return the list of hosts within a networks. This utility works for both IPv4 and IPv6.
  936. .. note::
  937. When running this command with a large IPv6 network, the command will
  938. take a long time to gather all of the hosts.
  939. Example:
  940. .. code-block:: jinja
  941. {{ '192.168.0.1/30' | network_hosts }}
  942. Returns:
  943. .. code-block:: python
  944. ["192.168.0.1", "192.168.0.2"]
  945. .. jinja_ref:: network_size
  946. ``network_size``
  947. ----------------
  948. .. versionadded:: 2017.7.0
  949. Return the size of the network. This utility works for both IPv4 and IPv6.
  950. Example:
  951. .. code-block:: jinja
  952. {{ '192.168.0.1/8' | network_size }}
  953. Returns:
  954. .. code-block:: python
  955. 16777216
  956. .. jinja_ref:: gen_mac
  957. ``gen_mac``
  958. -----------
  959. .. versionadded:: 2017.7.0
  960. Generates a MAC address with the defined OUI prefix.
  961. Common prefixes:
  962. - ``00:16:3E`` -- Xen
  963. - ``00:18:51`` -- OpenVZ
  964. - ``00:50:56`` -- VMware (manually generated)
  965. - ``52:54:00`` -- QEMU/KVM
  966. - ``AC:DE:48`` -- PRIVATE
  967. Example:
  968. .. code-block:: jinja
  969. {{ '00:50' | gen_mac }}
  970. Returns:
  971. .. code-block:: text
  972. 00:50:71:52:1C
  973. .. jinja_ref:: mac_str_to_bytes
  974. ``mac_str_to_bytes``
  975. --------------------
  976. .. versionadded:: 2017.7.0
  977. Converts a string representing a valid MAC address to bytes.
  978. Example:
  979. .. code-block:: jinja
  980. {{ '00:11:22:33:44:55' | mac_str_to_bytes }}
  981. .. note::
  982. This option may have adverse effects when using the default renderer,
  983. ``jinja|yaml``. This is due to the fact that YAML requires proper handling
  984. in regard to special characters. Please see the section on :ref:`YAML ASCII
  985. support <yaml_plain_ascii>` in the :ref:`YAML Idiosyncracies
  986. <yaml-idiosyncrasies>` documentation for more information.
  987. .. jinja_ref:: dns_check
  988. ``dns_check``
  989. -------------
  990. .. versionadded:: 2017.7.0
  991. Return the ip resolved by dns, but do not exit on failure, only raise an
  992. exception. Obeys system preference for IPv4/6 address resolution.
  993. Example:
  994. .. code-block:: jinja
  995. {{ 'www.google.com' | dns_check(port=443) }}
  996. Returns:
  997. .. code-block:: text
  998. '172.217.3.196'
  999. File filters
  1000. ------------
  1001. .. jinja_ref:: is_text_file
  1002. ``is_text_file``
  1003. ----------------
  1004. .. versionadded:: 2017.7.0
  1005. Return if a file is text.
  1006. Uses heuristics to guess whether the given file is text or binary,
  1007. by reading a single block of bytes from the file.
  1008. If more than 30% of the chars in the block are non-text, or there
  1009. are NUL ('\x00') bytes in the block, assume this is a binary file.
  1010. Example:
  1011. .. code-block:: jinja
  1012. {{ '/etc/salt/master' | is_text_file }}
  1013. Returns:
  1014. .. code-block:: python
  1015. True
  1016. .. jinja_ref:: is_binary_file
  1017. ``is_binary_file``
  1018. ------------------
  1019. .. versionadded:: 2017.7.0
  1020. Return if a file is binary.
  1021. Detects if the file is a binary, returns bool. Returns True if the file is
  1022. a bin, False if the file is not and None if the file is not available.
  1023. Example:
  1024. .. code-block:: jinja
  1025. {{ '/etc/salt/master' | is_binary_file }}
  1026. Returns:
  1027. .. code-block:: python
  1028. False
  1029. .. jinja_ref:: is_empty_file
  1030. ``is_empty_file``
  1031. -----------------
  1032. .. versionadded:: 2017.7.0
  1033. Return if a file is empty.
  1034. Example:
  1035. .. code-block:: jinja
  1036. {{ '/etc/salt/master' | is_empty_file }}
  1037. Returns:
  1038. .. code-block:: python
  1039. False
  1040. .. jinja_ref:: file_hashsum
  1041. ``file_hashsum``
  1042. ----------------
  1043. .. versionadded:: 2017.7.0
  1044. Return the hashsum of a file.
  1045. Example:
  1046. .. code-block:: jinja
  1047. {{ '/etc/salt/master' | file_hashsum }}
  1048. Returns:
  1049. .. code-block:: text
  1050. 02d4ef135514934759634f10079653252c7ad594ea97bd385480c532bca0fdda
  1051. .. jinja_ref:: list_files
  1052. ``list_files``
  1053. --------------
  1054. .. versionadded:: 2017.7.0
  1055. Return a recursive list of files under a specific path.
  1056. Example:
  1057. .. code-block:: jinja
  1058. {{ '/etc/salt/' | list_files | join('\n') }}
  1059. Returns:
  1060. .. code-block:: text
  1061. /etc/salt/master
  1062. /etc/salt/proxy
  1063. /etc/salt/minion
  1064. /etc/salt/pillar/top.sls
  1065. /etc/salt/pillar/device1.sls
  1066. .. jinja_ref:: path_join
  1067. ``path_join``
  1068. -------------
  1069. .. versionadded:: 2017.7.0
  1070. Joins absolute paths.
  1071. Example:
  1072. .. code-block:: jinja
  1073. {{ '/etc/salt/' | path_join('pillar', 'device1.sls') }}
  1074. Returns:
  1075. .. code-block:: text
  1076. /etc/salt/pillar/device1.sls
  1077. .. jinja_ref:: which
  1078. ``which``
  1079. ---------
  1080. .. versionadded:: 2017.7.0
  1081. Python clone of /usr/bin/which.
  1082. Example:
  1083. .. code-block:: jinja
  1084. {{ 'salt-master' | which }}
  1085. Returns:
  1086. .. code-block:: text
  1087. /usr/local/salt/virtualenv/bin/salt-master
  1088. Tests
  1089. =====
  1090. Saltstack extends `builtin tests`_ with these custom tests:
  1091. .. _`builtin tests`: https://jinja.palletsprojects.com/en/2.11.x/templates/#builtin-tests
  1092. .. jinja_ref:: equalto
  1093. ``equalto``
  1094. -----------
  1095. Tests the equality between two values.
  1096. Can be used in an ``if`` statement directly:
  1097. .. code-block:: jinja
  1098. {% if 1 is equalto(1) %}
  1099. < statements >
  1100. {% endif %}
  1101. If clause evaluates to ``True``
  1102. or with the ``selectattr`` filter:
  1103. .. code-block:: jinja
  1104. {{ [{'value': 1}, {'value': 2} , {'value': 3}] | selectattr('value', 'equalto', 3) | list }}
  1105. Returns:
  1106. .. code-block:: python
  1107. [{"value": 3}]
  1108. .. jinja_ref:: match
  1109. ``match``
  1110. ---------
  1111. Tests that a string matches the regex passed as an argument.
  1112. Can be used in a ``if`` statement directly:
  1113. .. code-block:: jinja
  1114. {% if 'a' is match('[a-b]') %}
  1115. < statements >
  1116. {% endif %}
  1117. If clause evaluates to ``True``
  1118. or with the ``selectattr`` filter:
  1119. .. code-block:: jinja
  1120. {{ [{'value': 'a'}, {'value': 'b'}, {'value': 'c'}] | selectattr('value', 'match', '[b-e]') | list }}
  1121. Returns:
  1122. .. code-block:: python
  1123. [{"value": "b"}, {"value": "c"}]
  1124. Test supports additional optional arguments: ``ignorecase``, ``multiline``
  1125. Escape filters
  1126. --------------
  1127. .. jinja_ref:: regex_escape
  1128. ``regex_escape``
  1129. ----------------
  1130. .. versionadded:: 2017.7.0
  1131. Allows escaping of strings so they can be interpreted literally by another function.
  1132. Example:
  1133. .. code-block:: jinja
  1134. regex_escape = {{ 'https://example.com?foo=bar%20baz' | regex_escape }}
  1135. will be rendered as:
  1136. .. code-block:: text
  1137. regex_escape = https\:\/\/example\.com\?foo\=bar\%20baz
  1138. Set Theory Filters
  1139. ------------------
  1140. .. jinja_ref:: unique
  1141. ``unique``
  1142. ----------
  1143. .. versionadded:: 2017.7.0
  1144. Performs set math using Jinja filters.
  1145. Example:
  1146. .. code-block:: jinja
  1147. unique = {{ ['foo', 'foo', 'bar'] | unique }}
  1148. will be rendered as:
  1149. .. code-block:: text
  1150. unique = ['foo', 'bar']
  1151. Jinja in Files
  1152. ==============
  1153. Jinja_ can be used in the same way in managed files:
  1154. .. code-block:: yaml
  1155. # redis.sls
  1156. /etc/redis/redis.conf:
  1157. file.managed:
  1158. - source: salt://redis.conf
  1159. - template: jinja
  1160. - context:
  1161. bind: 127.0.0.1
  1162. .. code-block:: jinja
  1163. # lib.sls
  1164. {% set port = 6379 %}
  1165. .. code-block:: ini
  1166. # redis.conf
  1167. {% from 'lib.sls' import port with context %}
  1168. port {{ port }}
  1169. bind {{ bind }}
  1170. As an example, configuration was pulled from the file context and from an
  1171. external template file.
  1172. .. note::
  1173. Macros and variables can be shared across templates. They should not be
  1174. starting with one or more underscores, and should be managed by one of the
  1175. following tags: `macro`, `set`, `load_yaml`, `load_json`, `import_yaml` and
  1176. `import_json`.
  1177. .. jinja_ref:: escaping-jinja
  1178. Escaping Jinja
  1179. ==============
  1180. Occasionally, it may be necessary to escape Jinja syntax. There are two ways
  1181. to do this in Jinja. One is escaping individual variables or strings and the
  1182. other is to escape entire blocks.
  1183. To escape a string commonly used in Jinja syntax such as ``{{``, you can use the
  1184. following syntax:
  1185. .. code-block:: jinja
  1186. {{ '{{' }}
  1187. For larger blocks that contain Jinja syntax that needs to be escaped, you can use
  1188. raw blocks:
  1189. .. code-block:: jinja
  1190. {% raw %}
  1191. some text that contains jinja characters that need to be escaped
  1192. {% endraw %}
  1193. See the `Escaping`_ section of Jinja's documentation to learn more.
  1194. A real-word example of needing to use raw tags to escape a larger block of code
  1195. is when using ``file.managed`` with the ``contents_pillar`` option to manage
  1196. files that contain something like consul-template, which shares a syntax subset
  1197. with Jinja. Raw blocks are necessary here because the Jinja in the pillar would
  1198. be rendered before the file.managed is ever called, so the Jinja syntax must be
  1199. escaped:
  1200. .. code-block:: jinja
  1201. {% raw %}
  1202. - contents_pillar: |
  1203. job "example-job" {
  1204. <snipped>
  1205. task "example" {
  1206. driver = "docker"
  1207. config {
  1208. image = "docker-registry.service.consul:5000/example-job:{{key "nomad/jobs/example-job/version"}}"
  1209. <snipped>
  1210. {% endraw %}
  1211. .. _`Escaping`: https://jinja.palletsprojects.com/en/2.11.x/templates/#escaping
  1212. .. jinja_ref:: calling-salt-functions
  1213. Calling Salt Functions
  1214. ======================
  1215. The Jinja renderer provides a shorthand lookup syntax for the ``salt``
  1216. dictionary of :term:`execution function <Execution Function>`.
  1217. .. versionadded:: 2014.7.0
  1218. .. code-block:: jinja
  1219. # The following two function calls are equivalent.
  1220. {{ salt['cmd.run']('whoami') }}
  1221. {{ salt.cmd.run('whoami') }}
  1222. .. jinja_ref:: debugging
  1223. Debugging
  1224. =========
  1225. The ``show_full_context`` function can be used to output all variables present
  1226. in the current Jinja context.
  1227. .. versionadded:: 2014.7.0
  1228. .. code-block:: jinja
  1229. Context is: {{ show_full_context()|yaml(False) }}
  1230. .. jinja_ref:: logs
  1231. Logs
  1232. ----
  1233. .. versionadded:: 2017.7.0
  1234. Yes, in Salt, one is able to debug a complex Jinja template using the logs.
  1235. For example, making the call:
  1236. .. code-block:: jinja
  1237. {%- do salt.log.error('testing jinja logging') -%}
  1238. Will insert the following message in the minion logs:
  1239. .. code-block:: text
  1240. 2017-02-01 01:24:40,728 [salt.module.logmod][ERROR ][3779] testing jinja logging
  1241. .. jinja_ref:: custom-execution-modules
  1242. Python Methods
  1243. ====================
  1244. A powerful feature of jinja that is only hinted at in the official jinja
  1245. documentation is that you can use the native python methods of the
  1246. variable type. Here is the python documentation for `string methods`_.
  1247. .. code-block:: jinja
  1248. {% set hostname,domain = grains.id.partition('.')[::2] %}{{ hostname }}
  1249. .. code-block:: jinja
  1250. {% set strings = grains.id.split('-') %}{{ strings[0] }}
  1251. .. _`string methods`: https://docs.python.org/2/library/stdtypes.html#string-methods
  1252. Custom Execution Modules
  1253. ========================
  1254. Custom execution modules can be used to supplement or replace complex Jinja. Many
  1255. tasks that require complex looping and logic are trivial when using Python
  1256. in a Salt execution module. Salt execution modules are easy to write and
  1257. distribute to Salt minions.
  1258. Functions in custom execution modules are available in the Salt execution
  1259. module dictionary just like the built-in execution modules:
  1260. .. code-block:: jinja
  1261. {{ salt['my_custom_module.my_custom_function']() }}
  1262. - :ref:`How to Convert Jinja Logic to an Execution Module <tutorial-jinja_to_execution-module>`
  1263. - :ref:`Writing Execution Modules <writing-execution-modules>`
  1264. .. jinja_ref:: custom-jinja-filters
  1265. Custom Jinja filters
  1266. ====================
  1267. Given that all execution modules are available in the Jinja template,
  1268. one can easily define a custom module as in the previous paragraph
  1269. and use it as a Jinja filter.
  1270. However, please note that it will not be accessible through the pipe.
  1271. For example, instead of:
  1272. .. code-block:: jinja
  1273. {{ my_variable | my_jinja_filter }}
  1274. The user will need to define ``my_jinja_filter`` function under an extension
  1275. module, say ``my_filters`` and use as:
  1276. .. code-block:: jinja
  1277. {{ salt.my_filters.my_jinja_filter(my_variable) }}
  1278. The greatest benefit is that you are able to access thousands of existing functions, e.g.:
  1279. - get the DNS AAAA records for a specific address using the :mod:`dnsutil <salt.modules.dnsutil>`:
  1280. .. code-block:: jinja
  1281. {{ salt.dnsutil.AAAA('www.google.com') }}
  1282. - retrieve a specific field value from a :mod:`Redis <salt.modules.modredis>` hash:
  1283. .. code-block:: jinja
  1284. {{ salt.redis.hget('foo_hash', 'bar_field') }}
  1285. - get the routes to ``0.0.0.0/0`` using the :mod:`NAPALM route <salt.modules.napalm_route>`:
  1286. .. code-block:: jinja
  1287. {{ salt.route.show('0.0.0.0/0') }}