1
0

index.rst 36 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981
  1. .. _understanding-jinja:
  2. ===================
  3. Understanding Jinja
  4. ===================
  5. `Jinja`_ is the default templating language in SLS files.
  6. .. _Jinja: http://jinja.pocoo.org/docs/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`: http://jinja.pocoo.org/docs/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: http://jinja.pocoo.org/docs/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`: http://jinja.pocoo.org/docs/templates/#template-inheritance
  108. .. _`Macros`: http://jinja.pocoo.org/docs/templates/#macros
  109. .. _`macro`: http://jinja.pocoo.org/docs/templates/#macros
  110. .. _`whitespace control`: http://jinja.pocoo.org/docs/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:: is_sorted
  381. ``is_sorted``
  382. -------------
  383. .. versionadded:: 2017.7.0
  384. Return is an iterable object is already sorted.
  385. Example:
  386. .. code-block:: jinja
  387. {{ [1, 2, 3] | is_sorted }}
  388. Returns:
  389. .. code-block:: python
  390. True
  391. .. jinja_ref:: compare_lists
  392. ``compare_lists``
  393. -----------------
  394. .. versionadded:: 2017.7.0
  395. Compare two lists and return a dictionary with the changes.
  396. Example:
  397. .. code-block:: jinja
  398. {{ [1, 2, 3] | compare_lists([1, 2, 4]) }}
  399. Returns:
  400. .. code-block:: python
  401. {'new': 4, 'old': 3}
  402. .. jinja_ref:: compare_dicts
  403. ``compare_dicts``
  404. -----------------
  405. .. versionadded:: 2017.7.0
  406. Compare two dictionaries and return a dictionary with the changes.
  407. Example:
  408. .. code-block:: jinja
  409. {{ {'a': 'b'} | compare_lists({'a': 'c'}) }}
  410. Returns:
  411. .. code-block:: python
  412. {'a': {'new': 'c', 'old': 'b'}}
  413. .. jinja_ref:: is_hex
  414. ``is_hex``
  415. ----------
  416. .. versionadded:: 2017.7.0
  417. Return True if the value is hexazecimal.
  418. Example:
  419. .. code-block:: jinja
  420. {{ '0xabcd' | is_hex }}
  421. {{ 'xyzt' | is_hex }}
  422. Returns:
  423. .. code-block:: python
  424. True
  425. False
  426. .. jinja_ref:: contains_whitespace
  427. ``contains_whitespace``
  428. -----------------------
  429. .. versionadded:: 2017.7.0
  430. Return True if a text contains whitespaces.
  431. Example:
  432. .. code-block:: jinja
  433. {{ 'abcd' | contains_whitespace }}
  434. {{ 'ab cd' | contains_whitespace }}
  435. Returns:
  436. .. code-block:: python
  437. False
  438. True
  439. .. jinja_ref:: substring_in_list
  440. ``substring_in_list``
  441. ---------------------
  442. .. versionadded:: 2017.7.0
  443. Return is a substring is found in a list of string values.
  444. Example:
  445. .. code-block:: jinja
  446. {{ 'abcd' | substring_in_list(['this', 'is', 'an abcd example']) }}
  447. Returns:
  448. .. code-block:: python
  449. True
  450. .. jinja_ref:: check_whitelist_blacklist
  451. ``check_whitelist_blacklist``
  452. -----------------------------
  453. .. versionadded:: 2017.7.0
  454. Check a whitelist and/or blacklist to see if the value matches it.
  455. This filter can be used with either a whitelist or a blacklist individually,
  456. or a whitelist and a blacklist can be passed simultaneously.
  457. If whitelist is used alone, value membership is checked against the
  458. whitelist only. If the value is found, the function returns ``True``.
  459. Otherwise, it returns ``False``.
  460. If blacklist is used alone, value membership is checked against the
  461. blacklist only. If the value is found, the function returns ``False``.
  462. Otherwise, it returns ``True``.
  463. If both a whitelist and a blacklist are provided, value membership in the
  464. blacklist will be examined first. If the value is not found in the blacklist,
  465. then the whitelist is checked. If the value isn't found in the whitelist,
  466. the function returns ``False``.
  467. Whitelist Example:
  468. .. code-block:: jinja
  469. {{ 5 | check_whitelist_blacklist(whitelist=[5, 6, 7]) }}
  470. Returns:
  471. .. code-block:: python
  472. True
  473. Blacklist Example:
  474. .. code-block:: jinja
  475. {{ 5 | check_whitelist_blacklist(blacklist=[5, 6, 7]) }}
  476. .. code-block:: python
  477. False
  478. .. jinja_ref:: date_format
  479. ``date_format``
  480. ---------------
  481. .. versionadded:: 2017.7.0
  482. Converts unix timestamp into human-readable string.
  483. Example:
  484. .. code-block:: jinja
  485. {{ 1457456400 | date_format }}
  486. {{ 1457456400 | date_format('%d.%m.%Y %H:%M') }}
  487. Returns:
  488. .. code-block:: text
  489. 2017-03-08
  490. 08.03.2017 17:00
  491. .. jinja_ref:: to_num
  492. ``to_num``
  493. ----------
  494. .. versionadded:: 2017.7.0
  495. .. versionadded:: 2018.3.0
  496. Renamed from ``str_to_num`` to ``to_num``.
  497. Converts a string to its numerical value.
  498. Example:
  499. .. code-block:: jinja
  500. {{ '5' | to_num }}
  501. Returns:
  502. .. code-block:: python
  503. 5
  504. .. jinja_ref:: to_bytes
  505. ``to_bytes``
  506. ------------
  507. .. versionadded:: 2017.7.0
  508. Converts string-type object to bytes.
  509. Example:
  510. .. code-block:: jinja
  511. {{ 'wall of text' | to_bytes }}
  512. .. note::
  513. This option may have adverse effects when using the default renderer,
  514. ``jinja|yaml``. This is due to the fact that YAML requires proper handling
  515. in regard to special characters. Please see the section on :ref:`YAML ASCII
  516. support <yaml_plain_ascii>` in the :ref:`YAML Idiosyncracies
  517. <yaml-idiosyncrasies>` documentation for more information.
  518. .. jinja_ref:: json_decode_list
  519. .. jinja_ref:: json_encode_list
  520. ``json_encode_list``
  521. --------------------
  522. .. versionadded:: 2017.7.0
  523. .. versionadded:: 2018.3.0
  524. Renamed from ``json_decode_list`` to ``json_encode_list``. When you encode
  525. something you get bytes, and when you decode, you get your locale's
  526. encoding (usually a ``unicode`` type). This filter was incorrectly-named
  527. when it was added. ``json_decode_list`` will be supported until the Neon
  528. release.
  529. .. deprecated:: 2018.3.3,2019.2.0
  530. The :jinja_ref:`tojson` filter accomplishes what this filter was designed
  531. to do, making this filter redundant.
  532. Recursively encodes all string elements of the list to bytes.
  533. Example:
  534. .. code-block:: jinja
  535. {{ [1, 2, 3] | json_encode_list }}
  536. Returns:
  537. .. code-block:: python
  538. [1, 2, 3]
  539. .. jinja_ref:: json_decode_dict
  540. .. jinja_ref:: json_encode_dict
  541. ``json_encode_dict``
  542. --------------------
  543. .. versionadded:: 2017.7.0
  544. .. versionadded:: 2018.3.0
  545. Renamed from ``json_decode_dict`` to ``json_encode_dict``. When you encode
  546. something you get bytes, and when you decode, you get your locale's
  547. encoding (usually a ``unicode`` type). This filter was incorrectly-named
  548. when it was added. ``json_decode_dict`` will be supported until the Neon
  549. release.
  550. .. deprecated:: 2018.3.3,2019.2.0
  551. The :jinja_ref:`tojson` filter accomplishes what this filter was designed
  552. to do, making this filter redundant.
  553. Recursively encodes all string items in the dictionary to bytes.
  554. Example:
  555. Assuming that ``pillar['foo']`` contains ``{u'a': u'\u0414'}``, and your locale
  556. is ``en_US.UTF-8``:
  557. .. code-block:: jinja
  558. {{ pillar['foo'] | json_encode_dict }}
  559. Returns:
  560. .. code-block:: python
  561. {'a': '\xd0\x94'}
  562. .. jinja_ref:: tojson
  563. ``tojson``
  564. ----------
  565. .. versionadded:: 2018.3.3,2019.2.0
  566. Dumps a data structure to JSON.
  567. This filter was added to provide this functionality to hosts which have a
  568. Jinja release older than version 2.9 installed. If Jinja 2.9 or newer is
  569. installed, then the upstream version of the filter will be used. See the
  570. `upstream docs`__ for more information.
  571. .. __: http://jinja.pocoo.org/docs/2.10/templates/#tojson
  572. .. jinja_ref:: random_hash
  573. ``random_hash``
  574. ---------------
  575. .. versionadded:: 2017.7.0
  576. .. versionadded:: 2018.3.0
  577. Renamed from ``rand_str`` to ``random_hash`` to more accurately describe
  578. what the filter does. ``rand_str`` will be supported until the Neon
  579. release.
  580. Generates a random number between 1 and the number passed to the filter, and
  581. then hashes it. The default hash type is the one specified by the minion's
  582. :conf_minion:`hash_type` config option, but an alternate hash type can be
  583. passed to the filter as an argument.
  584. Example:
  585. .. code-block:: jinja
  586. {% set num_range = 99999999 %}
  587. {{ num_range | random_hash }}
  588. {{ num_range | random_hash('sha512') }}
  589. Returns:
  590. .. code-block:: text
  591. 43ec517d68b6edd3015b3edc9a11367b
  592. d94a45acd81f8e3107d237dbc0d5d195f6a52a0d188bc0284c0763ece1eac9f9496fb6a531a296074c87b3540398dace1222b42e150e67c9301383fde3d66ae5
  593. .. jinja_ref:: md5
  594. ``md5``
  595. -------
  596. .. versionadded:: 2017.7.0
  597. Return the md5 digest of a string.
  598. Example:
  599. .. code-block:: jinja
  600. {{ 'random' | md5 }}
  601. Returns:
  602. .. code-block:: text
  603. 7ddf32e17a6ac5ce04a8ecbf782ca509
  604. .. jinja_ref:: sha256
  605. ``sha256``
  606. ----------
  607. .. versionadded:: 2017.7.0
  608. Return the sha256 digest of a string.
  609. Example:
  610. .. code-block:: jinja
  611. {{ 'random' | sha256 }}
  612. Returns:
  613. .. code-block:: text
  614. a441b15fe9a3cf56661190a0b93b9dec7d04127288cc87250967cf3b52894d11
  615. .. jinja_ref:: sha512
  616. ``sha512``
  617. ----------
  618. .. versionadded:: 2017.7.0
  619. Return the sha512 digest of a string.
  620. Example:
  621. .. code-block:: jinja
  622. {{ 'random' | sha512 }}
  623. Returns:
  624. .. code-block:: text
  625. 811a90e1c8e86c7b4c0eef5b2c0bf0ec1b19c4b1b5a242e6455be93787cb473cb7bc9b0fdeb960d00d5c6881c2094dd63c5c900ce9057255e2a4e271fc25fef1
  626. .. jinja_ref:: base64_encode
  627. ``base64_encode``
  628. -----------------
  629. .. versionadded:: 2017.7.0
  630. Encode a string as base64.
  631. Example:
  632. .. code-block:: jinja
  633. {{ 'random' | base64_encode }}
  634. Returns:
  635. .. code-block:: text
  636. cmFuZG9t
  637. .. jinja_ref:: base64_decode
  638. ``base64_decode``
  639. -----------------
  640. .. versionadded:: 2017.7.0
  641. Decode a base64-encoded string.
  642. .. code-block:: jinja
  643. {{ 'Z2V0IHNhbHRlZA==' | base64_decode }}
  644. Returns:
  645. .. code-block:: text
  646. get salted
  647. .. jinja_ref:: hmac
  648. ``hmac``
  649. --------
  650. .. versionadded:: 2017.7.0
  651. Verify a challenging hmac signature against a string / shared-secret. Returns
  652. a boolean value.
  653. Example:
  654. .. code-block:: jinja
  655. {{ 'get salted' | hmac('shared secret', 'eBWf9bstXg+NiP5AOwppB5HMvZiYMPzEM9W5YMm/AmQ=') }}
  656. Returns:
  657. .. code-block:: python
  658. True
  659. .. jinja_ref:: http_query
  660. ``http_query``
  661. --------------
  662. .. versionadded:: 2017.7.0
  663. Return the HTTP reply object from a URL.
  664. Example:
  665. .. code-block:: jinja
  666. {{ 'http://jsonplaceholder.typicode.com/posts/1' | http_query }}
  667. Returns:
  668. .. code-block:: python
  669. {
  670. 'body': '{
  671. "userId": 1,
  672. "id": 1,
  673. "title": "sunt aut facere repellat provident occaecati excepturi option reprehenderit",
  674. "body": "quia et suscipit\\nsuscipit recusandae consequuntur expedita et cum\\nreprehenderit molestiae ut ut quas totam\\nnostrum rerum est autem sunt rem eveniet architecto"
  675. }'
  676. }
  677. .. jinja_ref:: traverse
  678. ``traverse``
  679. ------------
  680. .. versionadded:: 2018.3.3
  681. Traverse a dict or list using a colon-delimited target string.
  682. The target 'foo:bar:0' will return data['foo']['bar'][0] if this value exists,
  683. and will otherwise return the provided default value.
  684. Example:
  685. .. code-block:: jinja
  686. {{ {'a1': {'b1': {'c1': 'foo'}}, 'a2': 'bar'} | traverse('a1:b1', 'default') }}
  687. Returns:
  688. .. code-block:: python
  689. {'c1': 'foo'}
  690. .. code-block:: jinja
  691. {{ {'a1': {'b1': {'c1': 'foo'}}, 'a2': 'bar'} | traverse('a2:b2', 'default') }}
  692. Returns:
  693. .. code-block:: python
  694. 'default'
  695. .. _`builtin filters`: http://jinja.pocoo.org/docs/templates/#builtin-filters
  696. .. _`timelib`: https://github.com/pediapress/timelib/
  697. Networking Filters
  698. ------------------
  699. The following networking-related filters are supported:
  700. .. jinja_ref:: is_ip
  701. ``is_ip``
  702. ---------
  703. .. versionadded:: 2017.7.0
  704. Return if a string is a valid IP Address.
  705. .. code-block:: jinja
  706. {{ '192.168.0.1' | is_ip }}
  707. Additionally accepts the following options:
  708. - global
  709. - link-local
  710. - loopback
  711. - multicast
  712. - private
  713. - public
  714. - reserved
  715. - site-local
  716. - unspecified
  717. Example - test if a string is a valid loopback IP address.
  718. .. code-block:: jinja
  719. {{ '192.168.0.1' | is_ip(options='loopback') }}
  720. .. jinja_ref:: is_ipv4
  721. ``is_ipv4``
  722. -----------
  723. .. versionadded:: 2017.7.0
  724. Returns if a string is a valid IPv4 address. Supports the same options
  725. as ``is_ip``.
  726. .. code-block:: jinja
  727. {{ '192.168.0.1' | is_ipv4 }}
  728. .. jinja_ref:: is_ipv6
  729. ``is_ipv6``
  730. -----------
  731. .. versionadded:: 2017.7.0
  732. Returns if a string is a valid IPv6 address. Supports the same options
  733. as ``is_ip``.
  734. .. code-block:: jinja
  735. {{ 'fe80::' | is_ipv6 }}
  736. .. jinja_ref:: ipaddr
  737. ``ipaddr``
  738. ----------
  739. .. versionadded:: 2017.7.0
  740. From a list, returns only valid IP entries. Supports the same options
  741. as ``is_ip``. The list can contains also IP interfaces/networks.
  742. Example:
  743. .. code-block:: jinja
  744. {{ ['192.168.0.1', 'foo', 'bar', 'fe80::'] | ipaddr }}
  745. Returns:
  746. .. code-block:: python
  747. ['192.168.0.1', 'fe80::']
  748. .. jinja_ref:: ipv4
  749. ``ipv4``
  750. --------
  751. .. versionadded:: 2017.7.0
  752. From a list, returns only valid IPv4 entries. Supports the same options
  753. as ``is_ip``. The list can contains also IP interfaces/networks.
  754. Example:
  755. .. code-block:: jinja
  756. {{ ['192.168.0.1', 'foo', 'bar', 'fe80::'] | ipv4 }}
  757. Returns:
  758. .. code-block:: python
  759. ['192.168.0.1']
  760. .. jinja_ref:: ipv6
  761. ``ipv6``
  762. --------
  763. .. versionadded:: 2017.7.0
  764. From a list, returns only valid IPv6 entries. Supports the same options
  765. as ``is_ip``. The list can contains also IP interfaces/networks.
  766. Example:
  767. .. code-block:: jinja
  768. {{ ['192.168.0.1', 'foo', 'bar', 'fe80::'] | ipv6 }}
  769. Returns:
  770. .. code-block:: python
  771. ['fe80::']
  772. .. jinja_ref:: network_hosts
  773. ``network_hosts``
  774. -----------------
  775. .. versionadded:: 2017.7.0
  776. Return the list of hosts within a networks. This utility works for both IPv4 and IPv6.
  777. .. note::
  778. When running this command with a large IPv6 network, the command will
  779. take a long time to gather all of the hosts.
  780. Example:
  781. .. code-block:: jinja
  782. {{ '192.168.0.1/30' | network_hosts }}
  783. Returns:
  784. .. code-block:: python
  785. ['192.168.0.1', '192.168.0.2']
  786. .. jinja_ref:: network_size
  787. ``network_size``
  788. ----------------
  789. .. versionadded:: 2017.7.0
  790. Return the size of the network. This utility works for both IPv4 and IPv6.
  791. Example:
  792. .. code-block:: jinja
  793. {{ '192.168.0.1/8' | network_size }}
  794. Returns:
  795. .. code-block:: python
  796. 16777216
  797. .. jinja_ref:: gen_mac
  798. ``gen_mac``
  799. -----------
  800. .. versionadded:: 2017.7.0
  801. Generates a MAC address with the defined OUI prefix.
  802. Common prefixes:
  803. - ``00:16:3E`` -- Xen
  804. - ``00:18:51`` -- OpenVZ
  805. - ``00:50:56`` -- VMware (manually generated)
  806. - ``52:54:00`` -- QEMU/KVM
  807. - ``AC:DE:48`` -- PRIVATE
  808. Example:
  809. .. code-block:: jinja
  810. {{ '00:50' | gen_mac }}
  811. Returns:
  812. .. code-block:: text
  813. 00:50:71:52:1C
  814. .. jinja_ref:: mac_str_to_bytes
  815. ``mac_str_to_bytes``
  816. --------------------
  817. .. versionadded:: 2017.7.0
  818. Converts a string representing a valid MAC address to bytes.
  819. Example:
  820. .. code-block:: jinja
  821. {{ '00:11:22:33:44:55' | mac_str_to_bytes }}
  822. .. note::
  823. This option may have adverse effects when using the default renderer,
  824. ``jinja|yaml``. This is due to the fact that YAML requires proper handling
  825. in regard to special characters. Please see the section on :ref:`YAML ASCII
  826. support <yaml_plain_ascii>` in the :ref:`YAML Idiosyncracies
  827. <yaml-idiosyncrasies>` documentation for more information.
  828. .. jinja_ref:: dns_check
  829. ``dns_check``
  830. -------------
  831. .. versionadded:: 2017.7.0
  832. Return the ip resolved by dns, but do not exit on failure, only raise an
  833. exception. Obeys system preference for IPv4/6 address resolution.
  834. Example:
  835. .. code-block:: jinja
  836. {{ 'www.google.com' | dns_check(port=443) }}
  837. Returns:
  838. .. code-block:: text
  839. '172.217.3.196'
  840. File filters
  841. ------------
  842. .. jinja_ref:: is_text_file
  843. ``is_text_file``
  844. ----------------
  845. .. versionadded:: 2017.7.0
  846. Return if a file is text.
  847. Uses heuristics to guess whether the given file is text or binary,
  848. by reading a single block of bytes from the file.
  849. If more than 30% of the chars in the block are non-text, or there
  850. are NUL ('\x00') bytes in the block, assume this is a binary file.
  851. Example:
  852. .. code-block:: jinja
  853. {{ '/etc/salt/master' | is_text_file }}
  854. Returns:
  855. .. code-block:: python
  856. True
  857. .. jinja_ref:: is_binary_file
  858. ``is_binary_file``
  859. ------------------
  860. .. versionadded:: 2017.7.0
  861. Return if a file is binary.
  862. Detects if the file is a binary, returns bool. Returns True if the file is
  863. a bin, False if the file is not and None if the file is not available.
  864. Example:
  865. .. code-block:: jinja
  866. {{ '/etc/salt/master' | is_binary_file }}
  867. Returns:
  868. .. code-block:: python
  869. False
  870. .. jinja_ref:: is_empty_file
  871. ``is_empty_file``
  872. -----------------
  873. .. versionadded:: 2017.7.0
  874. Return if a file is empty.
  875. Example:
  876. .. code-block:: jinja
  877. {{ '/etc/salt/master' | is_empty_file }}
  878. Returns:
  879. .. code-block:: python
  880. False
  881. .. jinja_ref:: file_hashsum
  882. ``file_hashsum``
  883. ----------------
  884. .. versionadded:: 2017.7.0
  885. Return the hashsum of a file.
  886. Example:
  887. .. code-block:: jinja
  888. {{ '/etc/salt/master' | file_hashsum }}
  889. Returns:
  890. .. code-block:: text
  891. 02d4ef135514934759634f10079653252c7ad594ea97bd385480c532bca0fdda
  892. .. jinja_ref:: list_files
  893. ``list_files``
  894. --------------
  895. .. versionadded:: 2017.7.0
  896. Return a recursive list of files under a specific path.
  897. Example:
  898. .. code-block:: jinja
  899. {{ '/etc/salt/' | list_files | join('\n') }}
  900. Returns:
  901. .. code-block:: text
  902. /etc/salt/master
  903. /etc/salt/proxy
  904. /etc/salt/minion
  905. /etc/salt/pillar/top.sls
  906. /etc/salt/pillar/device1.sls
  907. .. jinja_ref:: path_join
  908. ``path_join``
  909. -------------
  910. .. versionadded:: 2017.7.0
  911. Joins absolute paths.
  912. Example:
  913. .. code-block:: jinja
  914. {{ '/etc/salt/' | path_join('pillar', 'device1.sls') }}
  915. Returns:
  916. .. code-block:: text
  917. /etc/salt/pillar/device1.sls
  918. .. jinja_ref:: which
  919. ``which``
  920. ---------
  921. .. versionadded:: 2017.7.0
  922. Python clone of /usr/bin/which.
  923. Example:
  924. .. code-block:: jinja
  925. {{ 'salt-master' | which }}
  926. Returns:
  927. .. code-block:: text
  928. /usr/local/salt/virtualenv/bin/salt-master
  929. Tests
  930. =====
  931. Saltstack extends `builtin tests`_ with these custom tests:
  932. .. _`builtin tests`: http://jinja.pocoo.org/docs/templates/#builtin-tests
  933. .. jinja_ref:: equalto
  934. ``equalto``
  935. -----------
  936. Tests the equality between two values.
  937. Can be used in an ``if`` statement directly:
  938. .. code-block:: jinja
  939. {% if 1 is equalto(1) %}
  940. < statements >
  941. {% endif %}
  942. If clause evaluates to ``True``
  943. or with the ``selectattr`` filter:
  944. .. code-block:: jinja
  945. {{ [{'value': 1}, {'value': 2} , {'value': 3}] | selectattr('value', 'equalto', 3) | list }}
  946. Returns:
  947. .. code-block:: python
  948. [{'value': 3}]
  949. .. jinja_ref:: match
  950. ``match``
  951. ---------
  952. Tests that a string matches the regex passed as an argument.
  953. Can be used in a ``if`` statement directly:
  954. .. code-block:: jinja
  955. {% if 'a' is match('[a-b]') %}
  956. < statements >
  957. {% endif %}
  958. If clause evaluates to ``True``
  959. or with the ``selectattr`` filter:
  960. .. code-block:: jinja
  961. {{ [{'value': 'a'}, {'value': 'b'}, {'value': 'c'}] | selectattr('value', 'match', '[b-e]') | list }}
  962. Returns:
  963. .. code-block:: python
  964. [{'value': 'b'}, {'value': 'c'}]
  965. Test supports additional optional arguments: ``ignorecase``, ``multiline``
  966. Escape filters
  967. --------------
  968. .. jinja_ref:: regex_escape
  969. ``regex_escape``
  970. ----------------
  971. .. versionadded:: 2017.7.0
  972. Allows escaping of strings so they can be interpreted literally by another function.
  973. Example:
  974. .. code-block:: jinja
  975. regex_escape = {{ 'https://example.com?foo=bar%20baz' | regex_escape }}
  976. will be rendered as:
  977. .. code-block:: text
  978. regex_escape = https\:\/\/example\.com\?foo\=bar\%20baz
  979. Set Theory Filters
  980. ------------------
  981. .. jinja_ref:: unique
  982. ``unique``
  983. ----------
  984. .. versionadded:: 2017.7.0
  985. Performs set math using Jinja filters.
  986. Example:
  987. .. code-block:: jinja
  988. unique = {{ ['foo', 'foo', 'bar'] | unique }}
  989. will be rendered as:
  990. .. code-block:: text
  991. unique = ['foo', 'bar']
  992. Jinja in Files
  993. ==============
  994. Jinja_ can be used in the same way in managed files:
  995. .. code-block:: yaml
  996. # redis.sls
  997. /etc/redis/redis.conf:
  998. file.managed:
  999. - source: salt://redis.conf
  1000. - template: jinja
  1001. - context:
  1002. bind: 127.0.0.1
  1003. .. code-block:: jinja
  1004. # lib.sls
  1005. {% set port = 6379 %}
  1006. .. code-block:: ini
  1007. # redis.conf
  1008. {% from 'lib.sls' import port with context %}
  1009. port {{ port }}
  1010. bind {{ bind }}
  1011. As an example, configuration was pulled from the file context and from an
  1012. external template file.
  1013. .. note::
  1014. Macros and variables can be shared across templates. They should not be
  1015. starting with one or more underscores, and should be managed by one of the
  1016. following tags: `macro`, `set`, `load_yaml`, `load_json`, `import_yaml` and
  1017. `import_json`.
  1018. .. jinja_ref:: escaping-jinja
  1019. Escaping Jinja
  1020. ==============
  1021. Occasionally, it may be necessary to escape Jinja syntax. There are two ways
  1022. to do this in Jinja. One is escaping individual variables or strings and the
  1023. other is to escape entire blocks.
  1024. To escape a string commonly used in Jinja syntax such as ``{{``, you can use the
  1025. following syntax:
  1026. .. code-block:: jinja
  1027. {{ '{{' }}
  1028. For larger blocks that contain Jinja syntax that needs to be escaped, you can use
  1029. raw blocks:
  1030. .. code-block:: jinja
  1031. {% raw %}
  1032. some text that contains jinja characters that need to be escaped
  1033. {% endraw %}
  1034. See the `Escaping`_ section of Jinja's documentation to learn more.
  1035. A real-word example of needing to use raw tags to escape a larger block of code
  1036. is when using ``file.managed`` with the ``contents_pillar`` option to manage
  1037. files that contain something like consul-template, which shares a syntax subset
  1038. with Jinja. Raw blocks are necessary here because the Jinja in the pillar would
  1039. be rendered before the file.managed is ever called, so the Jinja syntax must be
  1040. escaped:
  1041. .. code-block:: jinja
  1042. {% raw %}
  1043. - contents_pillar: |
  1044. job "example-job" {
  1045. <snipped>
  1046. task "example" {
  1047. driver = "docker"
  1048. config {
  1049. image = "docker-registry.service.consul:5000/example-job:{{key "nomad/jobs/example-job/version"}}"
  1050. <snipped>
  1051. {% endraw %}
  1052. .. _`Escaping`: http://jinja.pocoo.org/docs/dev/templates/#escaping
  1053. .. jinja_ref:: calling-salt-functions
  1054. Calling Salt Functions
  1055. ======================
  1056. The Jinja renderer provides a shorthand lookup syntax for the ``salt``
  1057. dictionary of :term:`execution function <Execution Function>`.
  1058. .. versionadded:: 2014.7.0
  1059. .. code-block:: jinja
  1060. # The following two function calls are equivalent.
  1061. {{ salt['cmd.run']('whoami') }}
  1062. {{ salt.cmd.run('whoami') }}
  1063. .. jinja_ref:: debugging
  1064. Debugging
  1065. =========
  1066. The ``show_full_context`` function can be used to output all variables present
  1067. in the current Jinja context.
  1068. .. versionadded:: 2014.7.0
  1069. .. code-block:: jinja
  1070. Context is: {{ show_full_context()|yaml(False) }}
  1071. .. jinja_ref:: logs
  1072. Logs
  1073. ----
  1074. .. versionadded:: 2017.7.0
  1075. Yes, in Salt, one is able to debug a complex Jinja template using the logs.
  1076. For example, making the call:
  1077. .. code-block:: jinja
  1078. {%- do salt.log.error('testing jinja logging') -%}
  1079. Will insert the following message in the minion logs:
  1080. .. code-block:: text
  1081. 2017-02-01 01:24:40,728 [salt.module.logmod][ERROR ][3779] testing jinja logging
  1082. .. jinja_ref:: custom-execution-modules
  1083. Python Methods
  1084. ====================
  1085. A powerful feature of jinja that is only hinted at in the official jinja
  1086. documentation is that you can use the native python methods of the
  1087. variable type. Here is the python documentation for `string methods`_.
  1088. .. code-block:: jinja
  1089. {% set hostname,domain = grains.id.partition('.')[::2] %}{{ hostname }}
  1090. .. code-block:: jinja
  1091. {% set strings = grains.id.split('-') %}{{ strings[0] }}
  1092. .. _`string methods`: https://docs.python.org/2/library/stdtypes.html#string-methods
  1093. Custom Execution Modules
  1094. ========================
  1095. Custom execution modules can be used to supplement or replace complex Jinja. Many
  1096. tasks that require complex looping and logic are trivial when using Python
  1097. in a Salt execution module. Salt execution modules are easy to write and
  1098. distribute to Salt minions.
  1099. Functions in custom execution modules are available in the Salt execution
  1100. module dictionary just like the built-in execution modules:
  1101. .. code-block:: jinja
  1102. {{ salt['my_custom_module.my_custom_function']() }}
  1103. - :ref:`How to Convert Jinja Logic to an Execution Module <tutorial-jinja_to_execution-module>`
  1104. - :ref:`Writing Execution Modules <writing-execution-modules>`
  1105. .. jinja_ref:: custom-jinja-filters
  1106. Custom Jinja filters
  1107. ====================
  1108. Given that all execution modules are available in the Jinja template,
  1109. one can easily define a custom module as in the previous paragraph
  1110. and use it as a Jinja filter.
  1111. However, please note that it will not be accessible through the pipe.
  1112. For example, instead of:
  1113. .. code-block:: jinja
  1114. {{ my_variable | my_jinja_filter }}
  1115. The user will need to define ``my_jinja_filter`` function under an extension
  1116. module, say ``my_filters`` and use as:
  1117. .. code-block:: jinja
  1118. {{ salt.my_filters.my_jinja_filter(my_variable) }}
  1119. The greatest benefit is that you are able to access thousands of existing functions, e.g.:
  1120. - get the DNS AAAA records for a specific address using the :mod:`dnsutil <salt.modules.dnsutil>`:
  1121. .. code-block:: jinja
  1122. {{ salt.dnsutil.AAAA('www.google.com') }}
  1123. - retrieve a specific field value from a :mod:`Redis <salt.modules.modredis>` hash:
  1124. .. code-block:: jinja
  1125. {{ salt.redis.hget('foo_hash', 'bar_field') }}
  1126. - get the routes to ``0.0.0.0/0`` using the :mod:`NAPALM route <salt.modules.napalm_route>`:
  1127. .. code-block:: jinja
  1128. {{ salt.route.show('0.0.0.0/0') }}