1
0

index.rst 44 KB

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