index.rst 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261
  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:: method_call
  381. ``method_call``
  382. ---------------
  383. .. versionadded:: Neon
  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`: http://jinja.pocoo.org/docs/2.10/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 Neon
  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 Neon
  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. .. __: http://jinja.pocoo.org/docs/2.10/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 until the Neon
  607. release.
  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:: Neon
  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:: Neon
  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:: Neon
  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:: Neon
  686. Allows you to update a dictionary nested (deep) in another dictionary without having to worry if all the nested keys actually exist.
  687. Missing keys will automatically be created if they do not exist.
  688. The default delimiter for the keys is ':', however, with the `delimiter`-parameter, a different delimiter can be specified.
  689. Examples:
  690. .. code-block:: jinja
  691. Example 1:
  692. {%- set foo = {'bar': {'baz': {'qux': 1}}} %}
  693. {{ foo | update_dict_key_value('bar:baz', {'quux': 3}) }}
  694. Example 2:
  695. {{ {} | update_dict_key_value('bar:baz:qux', {'quux': 3}) }}
  696. .. code-block:: text
  697. Example 1:
  698. {'bar': {'baz': {'qux': 1, 'quux': 3}}}
  699. Example 2:
  700. {'bar': {'baz': {'qux': {'quux': 3}}}}
  701. .. jinja_ref:: md5
  702. ``md5``
  703. -------
  704. .. versionadded:: 2017.7.0
  705. Return the md5 digest of a string.
  706. Example:
  707. .. code-block:: jinja
  708. {{ 'random' | md5 }}
  709. Returns:
  710. .. code-block:: text
  711. 7ddf32e17a6ac5ce04a8ecbf782ca509
  712. .. jinja_ref:: sha256
  713. ``sha256``
  714. ----------
  715. .. versionadded:: 2017.7.0
  716. Return the sha256 digest of a string.
  717. Example:
  718. .. code-block:: jinja
  719. {{ 'random' | sha256 }}
  720. Returns:
  721. .. code-block:: text
  722. a441b15fe9a3cf56661190a0b93b9dec7d04127288cc87250967cf3b52894d11
  723. .. jinja_ref:: sha512
  724. ``sha512``
  725. ----------
  726. .. versionadded:: 2017.7.0
  727. Return the sha512 digest of a string.
  728. Example:
  729. .. code-block:: jinja
  730. {{ 'random' | sha512 }}
  731. Returns:
  732. .. code-block:: text
  733. 811a90e1c8e86c7b4c0eef5b2c0bf0ec1b19c4b1b5a242e6455be93787cb473cb7bc9b0fdeb960d00d5c6881c2094dd63c5c900ce9057255e2a4e271fc25fef1
  734. .. jinja_ref:: base64_encode
  735. ``base64_encode``
  736. -----------------
  737. .. versionadded:: 2017.7.0
  738. Encode a string as base64.
  739. Example:
  740. .. code-block:: jinja
  741. {{ 'random' | base64_encode }}
  742. Returns:
  743. .. code-block:: text
  744. cmFuZG9t
  745. .. jinja_ref:: base64_decode
  746. ``base64_decode``
  747. -----------------
  748. .. versionadded:: 2017.7.0
  749. Decode a base64-encoded string.
  750. .. code-block:: jinja
  751. {{ 'Z2V0IHNhbHRlZA==' | base64_decode }}
  752. Returns:
  753. .. code-block:: text
  754. get salted
  755. .. jinja_ref:: hmac
  756. ``hmac``
  757. --------
  758. .. versionadded:: 2017.7.0
  759. Verify a challenging hmac signature against a string / shared-secret. Returns
  760. a boolean value.
  761. Example:
  762. .. code-block:: jinja
  763. {{ 'get salted' | hmac('shared secret', 'eBWf9bstXg+NiP5AOwppB5HMvZiYMPzEM9W5YMm/AmQ=') }}
  764. Returns:
  765. .. code-block:: python
  766. True
  767. .. jinja_ref:: http_query
  768. ``http_query``
  769. --------------
  770. .. versionadded:: 2017.7.0
  771. Return the HTTP reply object from a URL.
  772. Example:
  773. .. code-block:: jinja
  774. {{ 'http://jsonplaceholder.typicode.com/posts/1' | http_query }}
  775. Returns:
  776. .. code-block:: python
  777. {
  778. 'body': '{
  779. "userId": 1,
  780. "id": 1,
  781. "title": "sunt aut facere repellat provident occaecati excepturi option reprehenderit",
  782. "body": "quia et suscipit\\nsuscipit recusandae consequuntur expedita et cum\\nreprehenderit molestiae ut ut quas totam\\nnostrum rerum est autem sunt rem eveniet architecto"
  783. }'
  784. }
  785. .. jinja_ref:: traverse
  786. ``traverse``
  787. ------------
  788. .. versionadded:: 2018.3.3
  789. Traverse a dict or list using a colon-delimited target string.
  790. The target 'foo:bar:0' will return data['foo']['bar'][0] if this value exists,
  791. and will otherwise return the provided default value.
  792. Example:
  793. .. code-block:: jinja
  794. {{ {'a1': {'b1': {'c1': 'foo'}}, 'a2': 'bar'} | traverse('a1:b1', 'default') }}
  795. Returns:
  796. .. code-block:: python
  797. {'c1': 'foo'}
  798. .. code-block:: jinja
  799. {{ {'a1': {'b1': {'c1': 'foo'}}, 'a2': 'bar'} | traverse('a2:b2', 'default') }}
  800. Returns:
  801. .. code-block:: python
  802. 'default'
  803. .. jinja_ref:: json_query
  804. ``json_query``
  805. --------------
  806. .. versionadded:: Neon
  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": "b", "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', 'b']
  829. Example 3: [80, 25, 22]
  830. .. _`builtin filters`: http://jinja.pocoo.org/docs/templates/#builtin-filters
  831. .. _`timelib`: https://github.com/pediapress/timelib/
  832. .. _`JMESPath language`: http://jmespath.org/
  833. .. _`jmespath`: https://github.com/jmespath/jmespath.py
  834. .. jinja_ref:: to_snake_case
  835. ``to_snake_case``
  836. -----------------
  837. .. versionadded:: Neon
  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:: Neon
  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. This function tries to connect to the address/port before considering it
  994. valid and therefor requires a port to test. The default port tested is 80.
  995. Example:
  996. .. code-block:: jinja
  997. {{ 'www.google.com' | dns_check(port=443) }}
  998. Returns:
  999. .. code-block:: text
  1000. '172.217.3.196'
  1001. File filters
  1002. ------------
  1003. .. jinja_ref:: connection_check
  1004. ``connection_check``
  1005. --------------------
  1006. .. versionadded:: Neon
  1007. Return the IP resolved by DNS. This is an alias of ``dns_check``.
  1008. .. jinja_ref:: is_text_file
  1009. ``is_text_file``
  1010. ----------------
  1011. .. versionadded:: 2017.7.0
  1012. Return if a file is text.
  1013. Uses heuristics to guess whether the given file is text or binary,
  1014. by reading a single block of bytes from the file.
  1015. If more than 30% of the chars in the block are non-text, or there
  1016. are NUL ('\x00') bytes in the block, assume this is a binary file.
  1017. Example:
  1018. .. code-block:: jinja
  1019. {{ '/etc/salt/master' | is_text_file }}
  1020. Returns:
  1021. .. code-block:: python
  1022. True
  1023. .. jinja_ref:: is_binary_file
  1024. ``is_binary_file``
  1025. ------------------
  1026. .. versionadded:: 2017.7.0
  1027. Return if a file is binary.
  1028. Detects if the file is a binary, returns bool. Returns True if the file is
  1029. a bin, False if the file is not and None if the file is not available.
  1030. Example:
  1031. .. code-block:: jinja
  1032. {{ '/etc/salt/master' | is_binary_file }}
  1033. Returns:
  1034. .. code-block:: python
  1035. False
  1036. .. jinja_ref:: is_empty_file
  1037. ``is_empty_file``
  1038. -----------------
  1039. .. versionadded:: 2017.7.0
  1040. Return if a file is empty.
  1041. Example:
  1042. .. code-block:: jinja
  1043. {{ '/etc/salt/master' | is_empty_file }}
  1044. Returns:
  1045. .. code-block:: python
  1046. False
  1047. .. jinja_ref:: file_hashsum
  1048. ``file_hashsum``
  1049. ----------------
  1050. .. versionadded:: 2017.7.0
  1051. Return the hashsum of a file.
  1052. Example:
  1053. .. code-block:: jinja
  1054. {{ '/etc/salt/master' | file_hashsum }}
  1055. Returns:
  1056. .. code-block:: text
  1057. 02d4ef135514934759634f10079653252c7ad594ea97bd385480c532bca0fdda
  1058. .. jinja_ref:: list_files
  1059. ``list_files``
  1060. --------------
  1061. .. versionadded:: 2017.7.0
  1062. Return a recursive list of files under a specific path.
  1063. Example:
  1064. .. code-block:: jinja
  1065. {{ '/etc/salt/' | list_files | join('\n') }}
  1066. Returns:
  1067. .. code-block:: text
  1068. /etc/salt/master
  1069. /etc/salt/proxy
  1070. /etc/salt/minion
  1071. /etc/salt/pillar/top.sls
  1072. /etc/salt/pillar/device1.sls
  1073. .. jinja_ref:: path_join
  1074. ``path_join``
  1075. -------------
  1076. .. versionadded:: 2017.7.0
  1077. Joins absolute paths.
  1078. Example:
  1079. .. code-block:: jinja
  1080. {{ '/etc/salt/' | path_join('pillar', 'device1.sls') }}
  1081. Returns:
  1082. .. code-block:: text
  1083. /etc/salt/pillar/device1.sls
  1084. .. jinja_ref:: which
  1085. ``which``
  1086. ---------
  1087. .. versionadded:: 2017.7.0
  1088. Python clone of /usr/bin/which.
  1089. Example:
  1090. .. code-block:: jinja
  1091. {{ 'salt-master' | which }}
  1092. Returns:
  1093. .. code-block:: text
  1094. /usr/local/salt/virtualenv/bin/salt-master
  1095. Tests
  1096. =====
  1097. Saltstack extends `builtin tests`_ with these custom tests:
  1098. .. _`builtin tests`: http://jinja.pocoo.org/docs/templates/#builtin-tests
  1099. .. jinja_ref:: equalto
  1100. ``equalto``
  1101. -----------
  1102. Tests the equality between two values.
  1103. Can be used in an ``if`` statement directly:
  1104. .. code-block:: jinja
  1105. {% if 1 is equalto(1) %}
  1106. < statements >
  1107. {% endif %}
  1108. If clause evaluates to ``True``
  1109. or with the ``selectattr`` filter:
  1110. .. code-block:: jinja
  1111. {{ [{'value': 1}, {'value': 2} , {'value': 3}] | selectattr('value', 'equalto', 3) | list }}
  1112. Returns:
  1113. .. code-block:: python
  1114. [{'value': 3}]
  1115. .. jinja_ref:: match
  1116. ``match``
  1117. ---------
  1118. Tests that a string matches the regex passed as an argument.
  1119. Can be used in a ``if`` statement directly:
  1120. .. code-block:: jinja
  1121. {% if 'a' is match('[a-b]') %}
  1122. < statements >
  1123. {% endif %}
  1124. If clause evaluates to ``True``
  1125. or with the ``selectattr`` filter:
  1126. .. code-block:: jinja
  1127. {{ [{'value': 'a'}, {'value': 'b'}, {'value': 'c'}] | selectattr('value', 'match', '[b-e]') | list }}
  1128. Returns:
  1129. .. code-block:: python
  1130. [{'value': 'b'}, {'value': 'c'}]
  1131. Test supports additional optional arguments: ``ignorecase``, ``multiline``
  1132. Escape filters
  1133. --------------
  1134. .. jinja_ref:: regex_escape
  1135. ``regex_escape``
  1136. ----------------
  1137. .. versionadded:: 2017.7.0
  1138. Allows escaping of strings so they can be interpreted literally by another function.
  1139. Example:
  1140. .. code-block:: jinja
  1141. regex_escape = {{ 'https://example.com?foo=bar%20baz' | regex_escape }}
  1142. will be rendered as:
  1143. .. code-block:: text
  1144. regex_escape = https\:\/\/example\.com\?foo\=bar\%20baz
  1145. Set Theory Filters
  1146. ------------------
  1147. .. jinja_ref:: unique
  1148. ``unique``
  1149. ----------
  1150. .. versionadded:: 2017.7.0
  1151. Performs set math using Jinja filters.
  1152. Example:
  1153. .. code-block:: jinja
  1154. unique = {{ ['foo', 'foo', 'bar'] | unique }}
  1155. will be rendered as:
  1156. .. code-block:: text
  1157. unique = ['foo', 'bar']
  1158. Jinja in Files
  1159. ==============
  1160. Jinja_ can be used in the same way in managed files:
  1161. .. code-block:: yaml
  1162. # redis.sls
  1163. /etc/redis/redis.conf:
  1164. file.managed:
  1165. - source: salt://redis.conf
  1166. - template: jinja
  1167. - context:
  1168. bind: 127.0.0.1
  1169. .. code-block:: jinja
  1170. # lib.sls
  1171. {% set port = 6379 %}
  1172. .. code-block:: ini
  1173. # redis.conf
  1174. {% from 'lib.sls' import port with context %}
  1175. port {{ port }}
  1176. bind {{ bind }}
  1177. As an example, configuration was pulled from the file context and from an
  1178. external template file.
  1179. .. note::
  1180. Macros and variables can be shared across templates. They should not be
  1181. starting with one or more underscores, and should be managed by one of the
  1182. following tags: `macro`, `set`, `load_yaml`, `load_json`, `import_yaml` and
  1183. `import_json`.
  1184. .. jinja_ref:: escaping-jinja
  1185. Escaping Jinja
  1186. ==============
  1187. Occasionally, it may be necessary to escape Jinja syntax. There are two ways
  1188. to do this in Jinja. One is escaping individual variables or strings and the
  1189. other is to escape entire blocks.
  1190. To escape a string commonly used in Jinja syntax such as ``{{``, you can use the
  1191. following syntax:
  1192. .. code-block:: jinja
  1193. {{ '{{' }}
  1194. For larger blocks that contain Jinja syntax that needs to be escaped, you can use
  1195. raw blocks:
  1196. .. code-block:: jinja
  1197. {% raw %}
  1198. some text that contains jinja characters that need to be escaped
  1199. {% endraw %}
  1200. See the `Escaping`_ section of Jinja's documentation to learn more.
  1201. A real-word example of needing to use raw tags to escape a larger block of code
  1202. is when using ``file.managed`` with the ``contents_pillar`` option to manage
  1203. files that contain something like consul-template, which shares a syntax subset
  1204. with Jinja. Raw blocks are necessary here because the Jinja in the pillar would
  1205. be rendered before the file.managed is ever called, so the Jinja syntax must be
  1206. escaped:
  1207. .. code-block:: jinja
  1208. {% raw %}
  1209. - contents_pillar: |
  1210. job "example-job" {
  1211. <snipped>
  1212. task "example" {
  1213. driver = "docker"
  1214. config {
  1215. image = "docker-registry.service.consul:5000/example-job:{{key "nomad/jobs/example-job/version"}}"
  1216. <snipped>
  1217. {% endraw %}
  1218. .. _`Escaping`: http://jinja.pocoo.org/docs/dev/templates/#escaping
  1219. .. jinja_ref:: calling-salt-functions
  1220. Calling Salt Functions
  1221. ======================
  1222. The Jinja renderer provides a shorthand lookup syntax for the ``salt``
  1223. dictionary of :term:`execution function <Execution Function>`.
  1224. .. versionadded:: 2014.7.0
  1225. .. code-block:: jinja
  1226. # The following two function calls are equivalent.
  1227. {{ salt['cmd.run']('whoami') }}
  1228. {{ salt.cmd.run('whoami') }}
  1229. .. jinja_ref:: debugging
  1230. Debugging
  1231. =========
  1232. The ``show_full_context`` function can be used to output all variables present
  1233. in the current Jinja context.
  1234. .. versionadded:: 2014.7.0
  1235. .. code-block:: jinja
  1236. Context is: {{ show_full_context()|yaml(False) }}
  1237. .. jinja_ref:: logs
  1238. Logs
  1239. ----
  1240. .. versionadded:: 2017.7.0
  1241. Yes, in Salt, one is able to debug a complex Jinja template using the logs.
  1242. For example, making the call:
  1243. .. code-block:: jinja
  1244. {%- do salt.log.error('testing jinja logging') -%}
  1245. Will insert the following message in the minion logs:
  1246. .. code-block:: text
  1247. 2017-02-01 01:24:40,728 [salt.module.logmod][ERROR ][3779] testing jinja logging
  1248. .. jinja_ref:: custom-execution-modules
  1249. Python Methods
  1250. ====================
  1251. A powerful feature of jinja that is only hinted at in the official jinja
  1252. documentation is that you can use the native python methods of the
  1253. variable type. Here is the python documentation for `string methods`_.
  1254. .. code-block:: jinja
  1255. {% set hostname,domain = grains.id.partition('.')[::2] %}{{ hostname }}
  1256. .. code-block:: jinja
  1257. {% set strings = grains.id.split('-') %}{{ strings[0] }}
  1258. .. _`string methods`: https://docs.python.org/2/library/stdtypes.html#string-methods
  1259. Custom Execution Modules
  1260. ========================
  1261. Custom execution modules can be used to supplement or replace complex Jinja. Many
  1262. tasks that require complex looping and logic are trivial when using Python
  1263. in a Salt execution module. Salt execution modules are easy to write and
  1264. distribute to Salt minions.
  1265. Functions in custom execution modules are available in the Salt execution
  1266. module dictionary just like the built-in execution modules:
  1267. .. code-block:: jinja
  1268. {{ salt['my_custom_module.my_custom_function']() }}
  1269. - :ref:`How to Convert Jinja Logic to an Execution Module <tutorial-jinja_to_execution-module>`
  1270. - :ref:`Writing Execution Modules <writing-execution-modules>`
  1271. .. jinja_ref:: custom-jinja-filters
  1272. Custom Jinja filters
  1273. ====================
  1274. Given that all execution modules are available in the Jinja template,
  1275. one can easily define a custom module as in the previous paragraph
  1276. and use it as a Jinja filter.
  1277. However, please note that it will not be accessible through the pipe.
  1278. For example, instead of:
  1279. .. code-block:: jinja
  1280. {{ my_variable | my_jinja_filter }}
  1281. The user will need to define ``my_jinja_filter`` function under an extension
  1282. module, say ``my_filters`` and use as:
  1283. .. code-block:: jinja
  1284. {{ salt.my_filters.my_jinja_filter(my_variable) }}
  1285. The greatest benefit is that you are able to access thousands of existing functions, e.g.:
  1286. - get the DNS AAAA records for a specific address using the :mod:`dnsutil <salt.modules.dnsutil>`:
  1287. .. code-block:: jinja
  1288. {{ salt.dnsutil.AAAA('www.google.com') }}
  1289. - retrieve a specific field value from a :mod:`Redis <salt.modules.modredis>` hash:
  1290. .. code-block:: jinja
  1291. {{ salt.redis.hget('foo_hash', 'bar_field') }}
  1292. - get the routes to ``0.0.0.0/0`` using the :mod:`NAPALM route <salt.modules.napalm_route>`:
  1293. .. code-block:: jinja
  1294. {{ salt.route.show('0.0.0.0/0') }}