1
0

index.rst 41 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198
  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 ``True`` if 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_dicts({'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 hexadecimal.
  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 ``True`` if 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 Aluminium
  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 Aluminium
  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 to ensure backwards
  579. compatibility but please use the preferred ``random_hash``.
  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:: set_dict_key_value
  594. ``set_dict_key_value``
  595. ----------------------
  596. ..versionadded:: 3000
  597. Allows you to set a value in a nested dictionary without having to worry if all the nested keys actually exist.
  598. Missing keys will be automatically created if they do not exist.
  599. The default delimiter for the keys is ':', however, with the `delimiter`-parameter, a different delimiter can be specified.
  600. Examples:
  601. .. code-block:: jinja
  602. Example 1:
  603. {%- set foo = {} %}
  604. {{ foo | set_dict_key_value('bar:baz', 42) }}
  605. Example 2:
  606. {{ {} | set_dict_key_value('bar.baz.qux', 42, delimiter='.') }}
  607. Returns:
  608. .. code-block:: text
  609. Example 1:
  610. {'bar': {'baz': 42}}
  611. Example 2:
  612. {'bar': {'baz': {'qux': 42}}}
  613. .. jinja_ref:: append_dict_key_value
  614. ``append_dict_key_value``
  615. -------------------------
  616. ..versionadded:: 3000
  617. 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.
  618. Missing keys will automatically be created if they do not exist.
  619. The default delimiter for the keys is ':', however, with the `delimiter`-parameter, a different delimiter can be specified.
  620. Examples:
  621. .. code-block:: jinja
  622. Example 1:
  623. {%- set foo = {'bar': {'baz': [1, 2]}} %}
  624. {{ foo | append_dict_key_value('bar:baz', 42) }}
  625. Example 2:
  626. {%- set foo = {} %}
  627. {{ foo | append_dict_key_value('bar:baz:qux', 42) }}
  628. Returns:
  629. .. code-block:: text
  630. Example 1:
  631. {'bar': {'baz': [1, 2, 42]}}
  632. Example 2:
  633. {'bar': {'baz': {'qux': [42]}}}
  634. .. jinja_ref:: extend_dict_key_value
  635. ``extend_dict_key_value``
  636. -------------------------
  637. ..versionadded:: 3000
  638. 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.
  639. Missing keys will automatically be created if they do not exist.
  640. The default delimiter for the keys is ':', however, with the `delimiter`-parameter, a different delimiter can be specified.
  641. Examples:
  642. .. code-block:: jinja
  643. Example 1:
  644. {%- set foo = {'bar': {'baz': [1, 2]}} %}
  645. {{ foo | extend_dict_key_value('bar:baz', [42, 42]) }}
  646. Example 2:
  647. {{ {} | extend_dict_key_value('bar:baz:qux', [42]) }}
  648. Returns:
  649. .. code-block:: text
  650. Example 1:
  651. {'bar': {'baz': [1, 2, 42, 42]}}
  652. Example 2:
  653. {'bar': {'baz': {'qux': [42]}}}
  654. .. jinja_ref:: update_dict_key_value
  655. ``update_dict_key_value``
  656. -------------------------
  657. ..versionadded:: 3000
  658. Allows you to update a dictionary nested (deep) in another dictionary without having to worry if all the nested keys actually exist.
  659. Missing keys will automatically be created if they do not exist.
  660. The default delimiter for the keys is ':', however, with the `delimiter`-parameter, a different delimiter can be specified.
  661. Examples:
  662. .. code-block:: jinja
  663. Example 1:
  664. {%- set foo = {'bar': {'baz': {'qux': 1}}} %}
  665. {{ foo | update_dict_key_value('bar:baz', {'quux': 3}) }}
  666. Example 2:
  667. {{ {} | update_dict_key_value('bar:baz:qux', {'quux': 3}) }}
  668. .. code-block:: text
  669. Example 1:
  670. {'bar': {'baz': {'qux': 1, 'quux': 3}}}
  671. Example 2:
  672. {'bar': {'baz': {'qux': {'quux': 3}}}}
  673. .. jinja_ref:: md5
  674. ``md5``
  675. -------
  676. .. versionadded:: 2017.7.0
  677. Return the md5 digest of a string.
  678. Example:
  679. .. code-block:: jinja
  680. {{ 'random' | md5 }}
  681. Returns:
  682. .. code-block:: text
  683. 7ddf32e17a6ac5ce04a8ecbf782ca509
  684. .. jinja_ref:: sha256
  685. ``sha256``
  686. ----------
  687. .. versionadded:: 2017.7.0
  688. Return the sha256 digest of a string.
  689. Example:
  690. .. code-block:: jinja
  691. {{ 'random' | sha256 }}
  692. Returns:
  693. .. code-block:: text
  694. a441b15fe9a3cf56661190a0b93b9dec7d04127288cc87250967cf3b52894d11
  695. .. jinja_ref:: sha512
  696. ``sha512``
  697. ----------
  698. .. versionadded:: 2017.7.0
  699. Return the sha512 digest of a string.
  700. Example:
  701. .. code-block:: jinja
  702. {{ 'random' | sha512 }}
  703. Returns:
  704. .. code-block:: text
  705. 811a90e1c8e86c7b4c0eef5b2c0bf0ec1b19c4b1b5a242e6455be93787cb473cb7bc9b0fdeb960d00d5c6881c2094dd63c5c900ce9057255e2a4e271fc25fef1
  706. .. jinja_ref:: base64_encode
  707. ``base64_encode``
  708. -----------------
  709. .. versionadded:: 2017.7.0
  710. Encode a string as base64.
  711. Example:
  712. .. code-block:: jinja
  713. {{ 'random' | base64_encode }}
  714. Returns:
  715. .. code-block:: text
  716. cmFuZG9t
  717. .. jinja_ref:: base64_decode
  718. ``base64_decode``
  719. -----------------
  720. .. versionadded:: 2017.7.0
  721. Decode a base64-encoded string.
  722. .. code-block:: jinja
  723. {{ 'Z2V0IHNhbHRlZA==' | base64_decode }}
  724. Returns:
  725. .. code-block:: text
  726. get salted
  727. .. jinja_ref:: hmac
  728. ``hmac``
  729. --------
  730. .. versionadded:: 2017.7.0
  731. Verify a challenging hmac signature against a string / shared-secret. Returns
  732. a boolean value.
  733. Example:
  734. .. code-block:: jinja
  735. {{ 'get salted' | hmac('shared secret', 'eBWf9bstXg+NiP5AOwppB5HMvZiYMPzEM9W5YMm/AmQ=') }}
  736. Returns:
  737. .. code-block:: python
  738. True
  739. .. jinja_ref:: http_query
  740. ``http_query``
  741. --------------
  742. .. versionadded:: 2017.7.0
  743. Return the HTTP reply object from a URL.
  744. Example:
  745. .. code-block:: jinja
  746. {{ 'http://jsonplaceholder.typicode.com/posts/1' | http_query }}
  747. Returns:
  748. .. code-block:: python
  749. {
  750. 'body': '{
  751. "userId": 1,
  752. "id": 1,
  753. "title": "sunt aut facere repellat provident occaecati excepturi option reprehenderit",
  754. "body": "quia et suscipit\\nsuscipit recusandae consequuntur expedita et cum\\nreprehenderit molestiae ut ut quas totam\\nnostrum rerum est autem sunt rem eveniet architecto"
  755. }'
  756. }
  757. .. jinja_ref:: traverse
  758. ``traverse``
  759. ------------
  760. .. versionadded:: 2018.3.3
  761. Traverse a dict or list using a colon-delimited target string.
  762. The target 'foo:bar:0' will return data['foo']['bar'][0] if this value exists,
  763. and will otherwise return the provided default value.
  764. Example:
  765. .. code-block:: jinja
  766. {{ {'a1': {'b1': {'c1': 'foo'}}, 'a2': 'bar'} | traverse('a1:b1', 'default') }}
  767. Returns:
  768. .. code-block:: python
  769. {'c1': 'foo'}
  770. .. code-block:: jinja
  771. {{ {'a1': {'b1': {'c1': 'foo'}}, 'a2': 'bar'} | traverse('a2:b2', 'default') }}
  772. Returns:
  773. .. code-block:: python
  774. 'default'
  775. .. jinja_ref:: json_query
  776. ``json_query``
  777. --------------
  778. .. versionadded:: 3000
  779. A port of Ansible ``json_query`` Jinja filter to make queries against JSON data using `JMESPath language`_.
  780. Could be used to filter ``pillar`` data, ``yaml`` maps, and together with :jinja_ref:`http_query`.
  781. Depends on the `jmespath`_ Python module.
  782. Examples:
  783. .. code-block:: jinja
  784. Example 1: {{ [1, 2, 3, 4, [5, 6]] | json_query('[]') }}
  785. Example 2: {{
  786. {"machines": [
  787. {"name": "a", "state": "running"},
  788. {"name": "b", "state": "stopped"},
  789. {"name": "c", "state": "running"}
  790. ]} | json_query("machines[?state=='running'].name") }}
  791. Example 3: {{
  792. {"services": [
  793. {"name": "http", "host": "1.2.3.4", "port": 80},
  794. {"name": "smtp", "host": "1.2.3.5", "port": 25},
  795. {"name": "ssh", "host": "1.2.3.6", "port": 22},
  796. ]} | json_query("services[].port") }}
  797. Returns:
  798. .. code-block:: text
  799. Example 1: [1, 2, 3, 4, 5, 6]
  800. Example 2: ['a', 'c']
  801. Example 3: [80, 25, 22]
  802. .. _`builtin filters`: http://jinja.pocoo.org/docs/templates/#builtin-filters
  803. .. _`timelib`: https://github.com/pediapress/timelib/
  804. .. _`JMESPath language`: http://jmespath.org/
  805. .. _`jmespath`: https://github.com/jmespath/jmespath.py
  806. .. jinja_ref:: to_snake_case
  807. ``to_snake_case``
  808. -----------------
  809. .. versionadded:: 3000
  810. Converts a string from camelCase (or CamelCase) to snake_case.
  811. .. code-block:: jinja
  812. Example: {{ camelsWillLoveThis | to_snake_case }}
  813. Returns:
  814. .. code-block:: text
  815. Example: camels_will_love_this
  816. .. jinja_ref:: to_camelcase
  817. ``to_camelcase``
  818. ----------------
  819. .. versionadded:: 3000
  820. Converts a string from snake_case to camelCase (or UpperCamelCase if so indicated).
  821. .. code-block:: jinja
  822. Example 1: {{ snake_case_for_the_win | to_camelcase }}
  823. Example 2: {{ snake_case_for_the_win | to_camelcase(uppercamel=True) }}
  824. Returns:
  825. .. code-block:: text
  826. Example 1: snakeCaseForTheWin
  827. Example 2: SnakeCaseForTheWin
  828. Networking Filters
  829. ------------------
  830. The following networking-related filters are supported:
  831. .. jinja_ref:: is_ip
  832. ``is_ip``
  833. ---------
  834. .. versionadded:: 2017.7.0
  835. Return if a string is a valid IP Address.
  836. .. code-block:: jinja
  837. {{ '192.168.0.1' | is_ip }}
  838. Additionally accepts the following options:
  839. - global
  840. - link-local
  841. - loopback
  842. - multicast
  843. - private
  844. - public
  845. - reserved
  846. - site-local
  847. - unspecified
  848. Example - test if a string is a valid loopback IP address.
  849. .. code-block:: jinja
  850. {{ '192.168.0.1' | is_ip(options='loopback') }}
  851. .. jinja_ref:: is_ipv4
  852. ``is_ipv4``
  853. -----------
  854. .. versionadded:: 2017.7.0
  855. Returns if a string is a valid IPv4 address. Supports the same options
  856. as ``is_ip``.
  857. .. code-block:: jinja
  858. {{ '192.168.0.1' | is_ipv4 }}
  859. .. jinja_ref:: is_ipv6
  860. ``is_ipv6``
  861. -----------
  862. .. versionadded:: 2017.7.0
  863. Returns if a string is a valid IPv6 address. Supports the same options
  864. as ``is_ip``.
  865. .. code-block:: jinja
  866. {{ 'fe80::' | is_ipv6 }}
  867. .. jinja_ref:: ipaddr
  868. ``ipaddr``
  869. ----------
  870. .. versionadded:: 2017.7.0
  871. From a list, returns only valid IP entries. Supports the same options
  872. as ``is_ip``. The list can contains also IP interfaces/networks.
  873. Example:
  874. .. code-block:: jinja
  875. {{ ['192.168.0.1', 'foo', 'bar', 'fe80::'] | ipaddr }}
  876. Returns:
  877. .. code-block:: python
  878. ['192.168.0.1', 'fe80::']
  879. .. jinja_ref:: ipv4
  880. ``ipv4``
  881. --------
  882. .. versionadded:: 2017.7.0
  883. From a list, returns only valid IPv4 entries. Supports the same options
  884. as ``is_ip``. The list can contains also IP interfaces/networks.
  885. Example:
  886. .. code-block:: jinja
  887. {{ ['192.168.0.1', 'foo', 'bar', 'fe80::'] | ipv4 }}
  888. Returns:
  889. .. code-block:: python
  890. ['192.168.0.1']
  891. .. jinja_ref:: ipv6
  892. ``ipv6``
  893. --------
  894. .. versionadded:: 2017.7.0
  895. From a list, returns only valid IPv6 entries. Supports the same options
  896. as ``is_ip``. The list can contains also IP interfaces/networks.
  897. Example:
  898. .. code-block:: jinja
  899. {{ ['192.168.0.1', 'foo', 'bar', 'fe80::'] | ipv6 }}
  900. Returns:
  901. .. code-block:: python
  902. ['fe80::']
  903. .. jinja_ref:: network_hosts
  904. ``network_hosts``
  905. -----------------
  906. .. versionadded:: 2017.7.0
  907. Return the list of hosts within a networks. This utility works for both IPv4 and IPv6.
  908. .. note::
  909. When running this command with a large IPv6 network, the command will
  910. take a long time to gather all of the hosts.
  911. Example:
  912. .. code-block:: jinja
  913. {{ '192.168.0.1/30' | network_hosts }}
  914. Returns:
  915. .. code-block:: python
  916. ['192.168.0.1', '192.168.0.2']
  917. .. jinja_ref:: network_size
  918. ``network_size``
  919. ----------------
  920. .. versionadded:: 2017.7.0
  921. Return the size of the network. This utility works for both IPv4 and IPv6.
  922. Example:
  923. .. code-block:: jinja
  924. {{ '192.168.0.1/8' | network_size }}
  925. Returns:
  926. .. code-block:: python
  927. 16777216
  928. .. jinja_ref:: gen_mac
  929. ``gen_mac``
  930. -----------
  931. .. versionadded:: 2017.7.0
  932. Generates a MAC address with the defined OUI prefix.
  933. Common prefixes:
  934. - ``00:16:3E`` -- Xen
  935. - ``00:18:51`` -- OpenVZ
  936. - ``00:50:56`` -- VMware (manually generated)
  937. - ``52:54:00`` -- QEMU/KVM
  938. - ``AC:DE:48`` -- PRIVATE
  939. Example:
  940. .. code-block:: jinja
  941. {{ '00:50' | gen_mac }}
  942. Returns:
  943. .. code-block:: text
  944. 00:50:71:52:1C
  945. .. jinja_ref:: mac_str_to_bytes
  946. ``mac_str_to_bytes``
  947. --------------------
  948. .. versionadded:: 2017.7.0
  949. Converts a string representing a valid MAC address to bytes.
  950. Example:
  951. .. code-block:: jinja
  952. {{ '00:11:22:33:44:55' | mac_str_to_bytes }}
  953. .. note::
  954. This option may have adverse effects when using the default renderer,
  955. ``jinja|yaml``. This is due to the fact that YAML requires proper handling
  956. in regard to special characters. Please see the section on :ref:`YAML ASCII
  957. support <yaml_plain_ascii>` in the :ref:`YAML Idiosyncracies
  958. <yaml-idiosyncrasies>` documentation for more information.
  959. .. jinja_ref:: dns_check
  960. ``dns_check``
  961. -------------
  962. .. versionadded:: 2017.7.0
  963. Return the ip resolved by dns, but do not exit on failure, only raise an
  964. exception. Obeys system preference for IPv4/6 address resolution.
  965. Example:
  966. .. code-block:: jinja
  967. {{ 'www.google.com' | dns_check(port=443) }}
  968. Returns:
  969. .. code-block:: text
  970. '172.217.3.196'
  971. File filters
  972. ------------
  973. .. jinja_ref:: is_text_file
  974. ``is_text_file``
  975. ----------------
  976. .. versionadded:: 2017.7.0
  977. Return if a file is text.
  978. Uses heuristics to guess whether the given file is text or binary,
  979. by reading a single block of bytes from the file.
  980. If more than 30% of the chars in the block are non-text, or there
  981. are NUL ('\x00') bytes in the block, assume this is a binary file.
  982. Example:
  983. .. code-block:: jinja
  984. {{ '/etc/salt/master' | is_text_file }}
  985. Returns:
  986. .. code-block:: python
  987. True
  988. .. jinja_ref:: is_binary_file
  989. ``is_binary_file``
  990. ------------------
  991. .. versionadded:: 2017.7.0
  992. Return if a file is binary.
  993. Detects if the file is a binary, returns bool. Returns True if the file is
  994. a bin, False if the file is not and None if the file is not available.
  995. Example:
  996. .. code-block:: jinja
  997. {{ '/etc/salt/master' | is_binary_file }}
  998. Returns:
  999. .. code-block:: python
  1000. False
  1001. .. jinja_ref:: is_empty_file
  1002. ``is_empty_file``
  1003. -----------------
  1004. .. versionadded:: 2017.7.0
  1005. Return if a file is empty.
  1006. Example:
  1007. .. code-block:: jinja
  1008. {{ '/etc/salt/master' | is_empty_file }}
  1009. Returns:
  1010. .. code-block:: python
  1011. False
  1012. .. jinja_ref:: file_hashsum
  1013. ``file_hashsum``
  1014. ----------------
  1015. .. versionadded:: 2017.7.0
  1016. Return the hashsum of a file.
  1017. Example:
  1018. .. code-block:: jinja
  1019. {{ '/etc/salt/master' | file_hashsum }}
  1020. Returns:
  1021. .. code-block:: text
  1022. 02d4ef135514934759634f10079653252c7ad594ea97bd385480c532bca0fdda
  1023. .. jinja_ref:: list_files
  1024. ``list_files``
  1025. --------------
  1026. .. versionadded:: 2017.7.0
  1027. Return a recursive list of files under a specific path.
  1028. Example:
  1029. .. code-block:: jinja
  1030. {{ '/etc/salt/' | list_files | join('\n') }}
  1031. Returns:
  1032. .. code-block:: text
  1033. /etc/salt/master
  1034. /etc/salt/proxy
  1035. /etc/salt/minion
  1036. /etc/salt/pillar/top.sls
  1037. /etc/salt/pillar/device1.sls
  1038. .. jinja_ref:: path_join
  1039. ``path_join``
  1040. -------------
  1041. .. versionadded:: 2017.7.0
  1042. Joins absolute paths.
  1043. Example:
  1044. .. code-block:: jinja
  1045. {{ '/etc/salt/' | path_join('pillar', 'device1.sls') }}
  1046. Returns:
  1047. .. code-block:: text
  1048. /etc/salt/pillar/device1.sls
  1049. .. jinja_ref:: which
  1050. ``which``
  1051. ---------
  1052. .. versionadded:: 2017.7.0
  1053. Python clone of /usr/bin/which.
  1054. Example:
  1055. .. code-block:: jinja
  1056. {{ 'salt-master' | which }}
  1057. Returns:
  1058. .. code-block:: text
  1059. /usr/local/salt/virtualenv/bin/salt-master
  1060. Tests
  1061. =====
  1062. Saltstack extends `builtin tests`_ with these custom tests:
  1063. .. _`builtin tests`: http://jinja.pocoo.org/docs/templates/#builtin-tests
  1064. .. jinja_ref:: equalto
  1065. ``equalto``
  1066. -----------
  1067. Tests the equality between two values.
  1068. Can be used in an ``if`` statement directly:
  1069. .. code-block:: jinja
  1070. {% if 1 is equalto(1) %}
  1071. < statements >
  1072. {% endif %}
  1073. If clause evaluates to ``True``
  1074. or with the ``selectattr`` filter:
  1075. .. code-block:: jinja
  1076. {{ [{'value': 1}, {'value': 2} , {'value': 3}] | selectattr('value', 'equalto', 3) | list }}
  1077. Returns:
  1078. .. code-block:: python
  1079. [{'value': 3}]
  1080. .. jinja_ref:: match
  1081. ``match``
  1082. ---------
  1083. Tests that a string matches the regex passed as an argument.
  1084. Can be used in a ``if`` statement directly:
  1085. .. code-block:: jinja
  1086. {% if 'a' is match('[a-b]') %}
  1087. < statements >
  1088. {% endif %}
  1089. If clause evaluates to ``True``
  1090. or with the ``selectattr`` filter:
  1091. .. code-block:: jinja
  1092. {{ [{'value': 'a'}, {'value': 'b'}, {'value': 'c'}] | selectattr('value', 'match', '[b-e]') | list }}
  1093. Returns:
  1094. .. code-block:: python
  1095. [{'value': 'b'}, {'value': 'c'}]
  1096. Test supports additional optional arguments: ``ignorecase``, ``multiline``
  1097. Escape filters
  1098. --------------
  1099. .. jinja_ref:: regex_escape
  1100. ``regex_escape``
  1101. ----------------
  1102. .. versionadded:: 2017.7.0
  1103. Allows escaping of strings so they can be interpreted literally by another function.
  1104. Example:
  1105. .. code-block:: jinja
  1106. regex_escape = {{ 'https://example.com?foo=bar%20baz' | regex_escape }}
  1107. will be rendered as:
  1108. .. code-block:: text
  1109. regex_escape = https\:\/\/example\.com\?foo\=bar\%20baz
  1110. Set Theory Filters
  1111. ------------------
  1112. .. jinja_ref:: unique
  1113. ``unique``
  1114. ----------
  1115. .. versionadded:: 2017.7.0
  1116. Performs set math using Jinja filters.
  1117. Example:
  1118. .. code-block:: jinja
  1119. unique = {{ ['foo', 'foo', 'bar'] | unique }}
  1120. will be rendered as:
  1121. .. code-block:: text
  1122. unique = ['foo', 'bar']
  1123. Jinja in Files
  1124. ==============
  1125. Jinja_ can be used in the same way in managed files:
  1126. .. code-block:: yaml
  1127. # redis.sls
  1128. /etc/redis/redis.conf:
  1129. file.managed:
  1130. - source: salt://redis.conf
  1131. - template: jinja
  1132. - context:
  1133. bind: 127.0.0.1
  1134. .. code-block:: jinja
  1135. # lib.sls
  1136. {% set port = 6379 %}
  1137. .. code-block:: ini
  1138. # redis.conf
  1139. {% from 'lib.sls' import port with context %}
  1140. port {{ port }}
  1141. bind {{ bind }}
  1142. As an example, configuration was pulled from the file context and from an
  1143. external template file.
  1144. .. note::
  1145. Macros and variables can be shared across templates. They should not be
  1146. starting with one or more underscores, and should be managed by one of the
  1147. following tags: `macro`, `set`, `load_yaml`, `load_json`, `import_yaml` and
  1148. `import_json`.
  1149. .. jinja_ref:: escaping-jinja
  1150. Escaping Jinja
  1151. ==============
  1152. Occasionally, it may be necessary to escape Jinja syntax. There are two ways
  1153. to do this in Jinja. One is escaping individual variables or strings and the
  1154. other is to escape entire blocks.
  1155. To escape a string commonly used in Jinja syntax such as ``{{``, you can use the
  1156. following syntax:
  1157. .. code-block:: jinja
  1158. {{ '{{' }}
  1159. For larger blocks that contain Jinja syntax that needs to be escaped, you can use
  1160. raw blocks:
  1161. .. code-block:: jinja
  1162. {% raw %}
  1163. some text that contains jinja characters that need to be escaped
  1164. {% endraw %}
  1165. See the `Escaping`_ section of Jinja's documentation to learn more.
  1166. A real-word example of needing to use raw tags to escape a larger block of code
  1167. is when using ``file.managed`` with the ``contents_pillar`` option to manage
  1168. files that contain something like consul-template, which shares a syntax subset
  1169. with Jinja. Raw blocks are necessary here because the Jinja in the pillar would
  1170. be rendered before the file.managed is ever called, so the Jinja syntax must be
  1171. escaped:
  1172. .. code-block:: jinja
  1173. {% raw %}
  1174. - contents_pillar: |
  1175. job "example-job" {
  1176. <snipped>
  1177. task "example" {
  1178. driver = "docker"
  1179. config {
  1180. image = "docker-registry.service.consul:5000/example-job:{{key "nomad/jobs/example-job/version"}}"
  1181. <snipped>
  1182. {% endraw %}
  1183. .. _`Escaping`: http://jinja.pocoo.org/docs/dev/templates/#escaping
  1184. .. jinja_ref:: calling-salt-functions
  1185. Calling Salt Functions
  1186. ======================
  1187. The Jinja renderer provides a shorthand lookup syntax for the ``salt``
  1188. dictionary of :term:`execution function <Execution Function>`.
  1189. .. versionadded:: 2014.7.0
  1190. .. code-block:: jinja
  1191. # The following two function calls are equivalent.
  1192. {{ salt['cmd.run']('whoami') }}
  1193. {{ salt.cmd.run('whoami') }}
  1194. .. jinja_ref:: debugging
  1195. Debugging
  1196. =========
  1197. The ``show_full_context`` function can be used to output all variables present
  1198. in the current Jinja context.
  1199. .. versionadded:: 2014.7.0
  1200. .. code-block:: jinja
  1201. Context is: {{ show_full_context()|yaml(False) }}
  1202. .. jinja_ref:: logs
  1203. Logs
  1204. ----
  1205. .. versionadded:: 2017.7.0
  1206. Yes, in Salt, one is able to debug a complex Jinja template using the logs.
  1207. For example, making the call:
  1208. .. code-block:: jinja
  1209. {%- do salt.log.error('testing jinja logging') -%}
  1210. Will insert the following message in the minion logs:
  1211. .. code-block:: text
  1212. 2017-02-01 01:24:40,728 [salt.module.logmod][ERROR ][3779] testing jinja logging
  1213. .. jinja_ref:: custom-execution-modules
  1214. Python Methods
  1215. ====================
  1216. A powerful feature of jinja that is only hinted at in the official jinja
  1217. documentation is that you can use the native python methods of the
  1218. variable type. Here is the python documentation for `string methods`_.
  1219. .. code-block:: jinja
  1220. {% set hostname,domain = grains.id.partition('.')[::2] %}{{ hostname }}
  1221. .. code-block:: jinja
  1222. {% set strings = grains.id.split('-') %}{{ strings[0] }}
  1223. .. _`string methods`: https://docs.python.org/2/library/stdtypes.html#string-methods
  1224. Custom Execution Modules
  1225. ========================
  1226. Custom execution modules can be used to supplement or replace complex Jinja. Many
  1227. tasks that require complex looping and logic are trivial when using Python
  1228. in a Salt execution module. Salt execution modules are easy to write and
  1229. distribute to Salt minions.
  1230. Functions in custom execution modules are available in the Salt execution
  1231. module dictionary just like the built-in execution modules:
  1232. .. code-block:: jinja
  1233. {{ salt['my_custom_module.my_custom_function']() }}
  1234. - :ref:`How to Convert Jinja Logic to an Execution Module <tutorial-jinja_to_execution-module>`
  1235. - :ref:`Writing Execution Modules <writing-execution-modules>`
  1236. .. jinja_ref:: custom-jinja-filters
  1237. Custom Jinja filters
  1238. ====================
  1239. Given that all execution modules are available in the Jinja template,
  1240. one can easily define a custom module as in the previous paragraph
  1241. and use it as a Jinja filter.
  1242. However, please note that it will not be accessible through the pipe.
  1243. For example, instead of:
  1244. .. code-block:: jinja
  1245. {{ my_variable | my_jinja_filter }}
  1246. The user will need to define ``my_jinja_filter`` function under an extension
  1247. module, say ``my_filters`` and use as:
  1248. .. code-block:: jinja
  1249. {{ salt.my_filters.my_jinja_filter(my_variable) }}
  1250. The greatest benefit is that you are able to access thousands of existing functions, e.g.:
  1251. - get the DNS AAAA records for a specific address using the :mod:`dnsutil <salt.modules.dnsutil>`:
  1252. .. code-block:: jinja
  1253. {{ salt.dnsutil.AAAA('www.google.com') }}
  1254. - retrieve a specific field value from a :mod:`Redis <salt.modules.modredis>` hash:
  1255. .. code-block:: jinja
  1256. {{ salt.redis.hget('foo_hash', 'bar_field') }}
  1257. - get the routes to ``0.0.0.0/0`` using the :mod:`NAPALM route <salt.modules.napalm_route>`:
  1258. .. code-block:: jinja
  1259. {{ salt.route.show('0.0.0.0/0') }}