requisites.rst 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255
  1. .. _requisites:
  2. ===========================================
  3. Requisites and Other Global State Arguments
  4. ===========================================
  5. Requisites
  6. ==========
  7. The Salt requisite system is used to create relationships between states. This
  8. provides a method to easily define inter-dependencies between states. These
  9. dependencies are expressed by declaring the relationships using state names
  10. and IDs or names. The generalized form of a requisite target is ``<state name>:
  11. <ID or name>``. The specific form is defined as a :ref:`Requisite Reference
  12. <requisite-reference>`.
  13. A common use-case for requisites is ensuring a package has been installed before
  14. trying to ensure the service is running. In the following example, Salt will
  15. ensure nginx has been installed before trying to manage the service. If the
  16. package could not be installed, Salt will not try to manage the service.
  17. .. code-block:: yaml
  18. nginx:
  19. pkg.installed:
  20. - name: nginx-light
  21. service.running:
  22. - enable: True
  23. - require:
  24. - pkg: nginx
  25. Without the requisite defined, salt would attempt to install the package and
  26. then attempt to manage the service even if the installation failed.
  27. These requisites always form dependencies in a predictable single direction.
  28. Each requisite has an alternate :ref:`<requisite>_in <requisites-in>` form that
  29. can be used to establish a "reverse" dependency--useful in for loops.
  30. In the end, a single dependency map is created and everything is executed in a
  31. finite and predictable order.
  32. .. _requisites-matching:
  33. Requisite matching
  34. ------------------
  35. Requisites typically need two pieces of information for matching:
  36. * The state module name (e.g. ``pkg`` or ``service``)
  37. * The state identifier (e.g. ``nginx`` or ``/etc/nginx/nginx.conf``)
  38. .. code-block:: yaml
  39. nginx:
  40. pkg.installed: []
  41. file.managed:
  42. - name: /etc/nginx/nginx.conf
  43. service.running:
  44. - require:
  45. - pkg: nginx
  46. - file: /etc/nginx/nginx.conf
  47. Glob matching in requisites
  48. ~~~~~~~~~~~~~~~~~~~~~~~~~~~
  49. .. versionadded:: 0.9.8
  50. Glob matching is supported in requisites. This is mostly useful for file
  51. changes. In the example below, a change in ``/etc/apache2/httpd.conf`` or
  52. ``/etc/apache2/sites-available/default.conf`` will reload/restart the service:
  53. .. code-block:: yaml
  54. apache2:
  55. service.running:
  56. - watch:
  57. - file: /etc/apache2/*
  58. Omitting state module in requisites
  59. -----------------------------------
  60. .. versionadded:: 2016.3.0
  61. In version 2016.3.0, the state module name was made optional. If the state module
  62. is omitted, all states matching the ID will be required, regardless of which
  63. module they are using.
  64. .. code-block:: yaml
  65. - require:
  66. - vim
  67. State target matching
  68. ~~~~~~~~~~~~~~~~~~~~~
  69. In order to understand how state targets are matched, it is helpful to know
  70. :ref:`how the state compiler is working <compiler-ordering>`. Consider the following
  71. example:
  72. .. code-block:: yaml
  73. Deploy server package:
  74. file.managed:
  75. - name: /usr/local/share/myapp.tar.xz
  76. - source: salt://myapp.tar.xz
  77. Extract server package:
  78. archive.extracted:
  79. - name: /usr/local/share/myapp
  80. - source: /usr/local/share/myapp.tar.xz
  81. - archive_format: tar
  82. - onchanges:
  83. - file: Deploy server package
  84. The first formula is converted to a dictionary which looks as follows (represented
  85. as YAML, some properties omitted for simplicity) as `High Data`:
  86. .. code-block:: yaml
  87. Deploy server package:
  88. file:
  89. - managed
  90. - name: /usr/local/share/myapp.tar.xz
  91. - source: salt://myapp.tar.xz
  92. The ``file.managed`` format used in the formula is essentially syntactic sugar:
  93. at the end, the target is ``file``, which is used in the ``Extract server package``
  94. state above.
  95. Identifier matching
  96. ~~~~~~~~~~~~~~~~~~~
  97. Requisites match on both the ID Declaration and the ``name`` parameter.
  98. This means that, in the "Deploy server package" example above, a ``require``
  99. requisite would match with ``Deploy server package`` *or* ``/usr/local/share/myapp.tar.xz``,
  100. so either of the following versions for "Extract server package" is correct:
  101. .. code-block:: yaml
  102. # (Archive arguments omitted for simplicity)
  103. # Match by ID declaration
  104. Extract server package:
  105. archive.extracted:
  106. - onchanges:
  107. - file: Deploy server package
  108. # Match by name parameter
  109. Extract server package:
  110. archive.extracted:
  111. - onchanges:
  112. - file: /usr/local/share/myapp.tar.xz
  113. Omitting state module in requisites
  114. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  115. .. versionadded:: 2016.3.0
  116. In version 2016.3.0, the state module name was made optional. If the state module
  117. is omitted, all states matching the ID will be required, regardless of which
  118. module they are using.
  119. .. code-block:: yaml
  120. - require:
  121. - vim
  122. Requisites Types
  123. ----------------
  124. All requisite types have a corresponding :ref:`<requisite>_in <requisites-in>` form:
  125. * :ref:`require <requisites-require>`: Requires that a list of target states succeed before execution
  126. * :ref:`onchanges <requisites-onchanges>`: Execute if any target states succeed with changes
  127. * :ref:`watch <requisites-watch>`: Similar to ``onchanges``; modifies state behavior using ``mod_watch``
  128. * :ref:`listen <requisites-listen>`: Similar to ``onchanges``; delays execution to end of state run using ``mod_wait``
  129. * :ref:`prereq <requisites-prereq>`: Execute prior to target state if target state expects to produce changes
  130. * :ref:`onfail <requisites-onfail>`: Execute only if a target state fails
  131. * :ref:`use <requisites-use>`: Copy arguments from another state
  132. Several requisite types have a corresponding :ref:`requisite_any <requisites-any>` form:
  133. * ``require_any``
  134. * ``watch_any``
  135. * ``onchanges_any``
  136. * ``onfail_any``
  137. Lastly, onfail has one special ``onfail_all`` form to account for when `AND`
  138. logic is desired instead of the default `OR` logic of onfail/onfail_any (which
  139. are equivalent).
  140. All requisites define specific relationships and always work with the dependency
  141. logic defined :ref:`above <requisites-matching>`.
  142. .. _requisites-require:
  143. require
  144. ~~~~~~~
  145. The use of ``require`` builds a dependency that prevents a state from executing
  146. until all required states execute successfully. If any required state fails,
  147. then the state will fail due to requisites.
  148. In the following example, the ``service`` state will not be checked unless both
  149. ``file`` states execute without failure.
  150. .. code-block:: yaml
  151. nginx:
  152. service.running:
  153. - require:
  154. - file: /etc/nginx/nginx.conf
  155. - file: /etc/nginx/conf.d/ssl.conf
  156. Require SLS File
  157. ++++++++++++++++
  158. As of Salt 0.16.0, it is possible to require an entire sls file. Do this by first
  159. including the sls file and then setting a state to ``require`` the included sls
  160. file:
  161. .. code-block:: yaml
  162. include:
  163. - foo
  164. bar:
  165. pkg.installed:
  166. - require:
  167. - sls: foo
  168. This will add a ``require`` to all of the state declarations found in the given
  169. sls file. This means that ``bar`` will ``require`` every state within ``foo``.
  170. This makes it very easy to batch large groups of states easily in any requisite
  171. statement.
  172. .. _requisites-onchanges:
  173. onchanges
  174. ~~~~~~~~~
  175. .. versionadded:: 2014.7.0
  176. The ``onchanges`` requisite makes a state only apply if the required states
  177. generate changes, and if the watched state's "result" is ``True`` (does not fail).
  178. This can be a useful way to execute a post hook after changing aspects of a system.
  179. If a state has multiple ``onchanges`` requisites then the state will trigger
  180. if any of the watched states changes.
  181. .. code-block:: yaml
  182. myservice:
  183. file.managed:
  184. - name: /etc/myservice/myservice.conf
  185. - source: salt://myservice/files/myservice.conf
  186. cmd.run:
  187. - name: /usr/local/sbin/run-build
  188. - onchanges:
  189. - file: /etc/myservice/myservice.conf
  190. In the example above, ``cmd.run`` will run only if there are changes in the
  191. ``file.managed`` state.
  192. An easy mistake to make is using ``onchanges_in`` when ``onchanges`` is the
  193. correct choice, as seen in this next example.
  194. .. code-block:: yaml
  195. myservice:
  196. file.managed:
  197. - name: /etc/myservice/myservice.conf
  198. - source: salt://myservice/files/myservice.conf
  199. cmd.run:
  200. - name: /usr/local/sbin/run-build
  201. - onchanges_in: # <-- broken logic
  202. - file: /etc/myservice/myservice.conf
  203. This will set up a requisite relationship in which the ``cmd.run`` state
  204. always executes, and the ``file.managed`` state only executes if the
  205. ``cmd.run`` state has changes (which it always will, since the ``cmd.run``
  206. state includes the command results as changes).
  207. It may semantically seem like the ``cmd.run`` state should only run
  208. when there are changes in the file state, but remember that requisite
  209. relationships involve one state watching another state, and a
  210. :ref:`requisite_in <requisites-onchanges-in>` does the opposite: it forces
  211. the specified state to watch the state with the ``requisite_in``.
  212. .. _requisites-watch:
  213. watch
  214. ~~~~~
  215. A ``watch`` requisite is used to add additional behavior when there are changes
  216. in other states. This is done using the ``mod_watch`` function available from
  217. the execution module and will execute any time a watched state changes.
  218. .. note::
  219. If a state should only execute when another state has changes, and
  220. otherwise do nothing, the ``onchanges`` requisite should be used instead
  221. of ``watch``. ``watch`` is designed to add *additional* behavior when
  222. there are changes, but otherwise the state executes normally.
  223. A good example of using ``watch`` is with a :mod:`service.running
  224. <salt.states.service.running>` state. When a service watches a state, then
  225. the service is reloaded/restarted when the watched state changes, in addition
  226. to Salt ensuring that the service is running.
  227. .. code-block:: yaml
  228. ntpd:
  229. service.running:
  230. - watch:
  231. - file: /etc/ntp.conf
  232. file.managed:
  233. - name: /etc/ntp.conf
  234. - source: salt://ntp/files/ntp.conf
  235. Another useful example of ``watch`` is using salt to ensure a configuration file
  236. is present and in a correct state, ensure the service is running, and trigger
  237. ``service nginx reload`` instead of ``service nginx restart`` in order to avoid
  238. dropping any connections.
  239. .. code-block:: yaml
  240. nginx:
  241. service.running:
  242. - reload: True
  243. - watch:
  244. - file: nginx
  245. file.managed:
  246. - name: /etc/nginx/conf.d/tls-settings.conf
  247. - source: salt://nginx/files/tls-settings.conf
  248. .. note::
  249. Not all state modules contain ``mod_watch``. If ``mod_watch`` is absent
  250. from the watching state module, the ``watch`` requisite behaves exactly
  251. like a ``require`` requisite.
  252. The state containing the ``watch`` requisite is defined as the watching
  253. state. The state specified in the ``watch`` statement is defined as the watched
  254. state. When the watched state executes, it will return a dictionary containing
  255. a key named "changes". Here are two examples of state return dictionaries,
  256. shown in json for clarity:
  257. .. code-block:: json
  258. {
  259. "local": {
  260. "file_|-/tmp/foo_|-/tmp/foo_|-directory": {
  261. "comment": "Directory /tmp/foo updated",
  262. "__run_num__": 0,
  263. "changes": {
  264. "user": "bar"
  265. },
  266. "name": "/tmp/foo",
  267. "result": true
  268. }
  269. }
  270. }
  271. {
  272. "local": {
  273. "pkgrepo_|-salt-minion_|-salt-minion_|-managed": {
  274. "comment": "Package repo 'salt-minion' already configured",
  275. "__run_num__": 0,
  276. "changes": {},
  277. "name": "salt-minion",
  278. "result": true
  279. }
  280. }
  281. }
  282. If the "result" of the watched state is ``True``, the watching state *will
  283. execute normally*, and if it is ``False``, the watching state will never run.
  284. This part of ``watch`` mirrors the functionality of the ``require`` requisite.
  285. If the "result" of the watched state is ``True`` *and* the "changes"
  286. key contains a populated dictionary (changes occurred in the watched state),
  287. then the ``watch`` requisite can add additional behavior. This additional
  288. behavior is defined by the ``mod_watch`` function within the watching state
  289. module. If the ``mod_watch`` function exists in the watching state module, it
  290. will be called *in addition to* the normal watching state. The return data
  291. from the ``mod_watch`` function is what will be returned to the master in this
  292. case; the return data from the main watching function is discarded.
  293. If the "changes" key contains an empty dictionary, the ``watch`` requisite acts
  294. exactly like the ``require`` requisite (the watching state will execute if
  295. "result" is ``True``, and fail if "result" is ``False`` in the watched state).
  296. .. note::
  297. If the watching state ``changes`` key contains values, then ``mod_watch``
  298. will not be called. If you're using ``watch`` or ``watch_in`` then it's a
  299. good idea to have a state that only enforces one attribute - such as
  300. splitting out ``service.running`` into its own state and have
  301. ``service.enabled`` in another.
  302. One common source of confusion is expecting ``mod_watch`` to be called for
  303. every necessary change. You might be tempted to write something like this:
  304. .. code-block:: yaml
  305. httpd:
  306. service.running:
  307. - enable: True
  308. - watch:
  309. - file: httpd-config
  310. httpd-config:
  311. file.managed:
  312. - name: /etc/httpd/conf/httpd.conf
  313. - source: salt://httpd/files/apache.conf
  314. If your service is already running but not enabled, you might expect that Salt
  315. will be able to tell that since the config file changed your service needs to
  316. be restarted. This is not the case. Because the service needs to be enabled,
  317. that change will be made and ``mod_watch`` will never be triggered. In this
  318. case, changes to your ``apache.conf`` will fail to be loaded. If you want to
  319. ensure that your service always reloads the correct way to handle this is
  320. either ensure that your service is not running before applying your state, or
  321. simply make sure that ``service.running`` is in a state on its own:
  322. .. code-block:: yaml
  323. enable-httpd:
  324. service.enabled:
  325. - name: httpd
  326. start-httpd:
  327. service.running:
  328. - name: httpd
  329. - watch:
  330. - file: httpd-config
  331. httpd-config:
  332. file.managed:
  333. - name: /etc/httpd/conf/httpd.conf
  334. - source: salt://httpd/files/apache.conf
  335. Now that ``service.running`` is its own state, changes to ``service.enabled``
  336. will no longer prevent ``mod_watch`` from getting triggered, so your ``httpd``
  337. service will get restarted like you want.
  338. .. _requisites-listen:
  339. listen
  340. ~~~~~~
  341. .. versionadded:: 2014.7.0
  342. A ``listen`` requisite is used to trigger the ``mod_wait`` function of an
  343. execution module. Rather than modifying execution order, the ``mod_wait`` state
  344. created by ``listen`` will execute at the end of the state run.
  345. .. code-block:: yaml
  346. restart-apache2:
  347. service.running:
  348. - name: apache2
  349. - listen:
  350. - file: /etc/apache2/apache2.conf
  351. configure-apache2:
  352. file.managed:
  353. - name: /etc/apache2/apache2.conf
  354. - source: salt://apache2/apache2.conf
  355. This example will cause apache2 to restart when the apache2.conf file is
  356. changed, but the apache2 restart will happen at the end of the state run.
  357. .. code-block:: yaml
  358. restart-apache2:
  359. service.running:
  360. - name: apache2
  361. configure-apache2:
  362. file.managed:
  363. - name: /etc/apache2/apache2.conf
  364. - source: salt://apache2/apache2.conf
  365. - listen_in:
  366. - service: apache2
  367. This example does the same as the above example, but puts the state argument
  368. on the file resource, rather than the service resource.
  369. .. _requisites-prereq:
  370. prereq
  371. ~~~~~~
  372. .. versionadded:: 0.16.0
  373. The ``prereq`` requisite works similar to ``onchanges`` except that it uses the
  374. result from ``test=True`` on the observed state to determine if it should run
  375. prior to the observed state being run.
  376. The best way to define how ``prereq`` operates is displayed in the following
  377. practical example: When a service should be shut down because underlying code
  378. is going to change, the service should be off-line while the update occurs. In
  379. this example, ``graceful-down`` is the pre-requiring state and ``site-code``
  380. is the pre-required state.
  381. .. code-block:: yaml
  382. graceful-down:
  383. cmd.run:
  384. - name: service apache graceful
  385. - prereq:
  386. - file: site-code
  387. site-code:
  388. file.recurse:
  389. - name: /opt/site_code
  390. - source: salt://site/code
  391. In this case, the apache server will only be shut down if the site-code state
  392. expects to deploy fresh code via the file.recurse call. The site-code deployment
  393. will only be executed if the graceful-down run completes successfully.
  394. When a ``prereq`` requisite is evaluated, the pre-required state reports if it
  395. expects to have any changes. It does this by running the pre-required single
  396. state as a test-run by enabling ``test=True``. This test-run will return a
  397. dictionary containing a key named "changes". (See the ``watch`` section above
  398. for examples of "changes" dictionaries.)
  399. If the "changes" key contains a populated dictionary, it means that the
  400. pre-required state expects changes to occur when the state is actually
  401. executed, as opposed to the test-run. The pre-requiring state will now
  402. run. If the pre-requiring state executes successfully, the pre-required
  403. state will then execute. If the pre-requiring state fails, the pre-required
  404. state will not execute.
  405. If the "changes" key contains an empty dictionary, this means that changes are
  406. not expected by the pre-required state. Neither the pre-required state nor the
  407. pre-requiring state will run.
  408. .. _requisites-onfail:
  409. onfail
  410. ~~~~~~
  411. .. versionadded:: 2014.7.0
  412. The ``onfail`` requisite allows for reactions to happen strictly as a response
  413. to the failure of another state. This can be used in a number of ways, such as
  414. sending a notification or attempting an alternate task or thread of tasks when
  415. an important state fails.
  416. The ``onfail`` requisite is applied in the same way as ``require`` and ``watch``:
  417. .. code-block:: yaml
  418. primary_mount:
  419. mount.mounted:
  420. - name: /mnt/share
  421. - device: 10.0.0.45:/share
  422. - fstype: nfs
  423. backup_mount:
  424. mount.mounted:
  425. - name: /mnt/share
  426. - device: 192.168.40.34:/share
  427. - fstype: nfs
  428. - onfail:
  429. - mount: primary_mount
  430. .. code-block:: yaml
  431. build_site:
  432. cmd.run:
  433. - name: /srv/web/app/build_site
  434. notify-build_failure:
  435. hipchat.send_message:
  436. - room_id: 123456
  437. - message: "Building website fail on {{ salt.grains.get('id') }}"
  438. The default behavior of the ``onfail`` when multiple requisites are listed is
  439. the opposite of other requisites in the salt state engine, it acts by default
  440. like ``any()`` instead of ``all()``. This means that when you list multiple
  441. onfail requisites on a state, if *any* fail the requisite will be satisfied.
  442. If you instead need *all* logic to be applied, you can use ``onfail_all``
  443. form:
  444. .. code-block:: yaml
  445. test_site_a:
  446. cmd.run:
  447. - name: ping -c1 10.0.0.1
  448. test_site_b:
  449. cmd.run:
  450. - name: ping -c1 10.0.0.2
  451. notify_site_down:
  452. hipchat.send_message:
  453. - room_id: 123456
  454. - message: "Both primary and backup sites are down!"
  455. - onfail_all:
  456. - cmd: test_site_a
  457. - cmd: test_site_b
  458. In this contrived example `notify_site_down` will run when both 10.0.0.1 and
  459. 10.0.0.2 fail to respond to ping.
  460. .. note::
  461. Setting failhard (:ref:`globally <global-failhard>` or in
  462. :ref:`the failing state <state-level-failhard>`) to ``True`` will cause
  463. ``onfail``, ``onfail_in`` and ``onfail_any`` requisites to be ignored.
  464. If you want to combine a global failhard set to True with ``onfail``,
  465. ``onfail_in`` or ``onfail_any``, you will have to explicitly set failhard
  466. to ``False`` (overriding the global setting) in the state that could fail.
  467. .. note::
  468. Beginning in the ``2016.11.0`` release of Salt, ``onfail`` uses OR logic for
  469. multiple listed ``onfail`` requisites. Prior to the ``2016.11.0`` release,
  470. ``onfail`` used AND logic. See `Issue #22370`_ for more information.
  471. Beginning in the ``Neon`` release of Salt, a new ``onfail_all`` requisite
  472. form is available if AND logic is desired.
  473. .. _Issue #22370: https://github.com/saltstack/salt/issues/22370
  474. .. _requisites-use:
  475. use
  476. ~~~
  477. The ``use`` requisite is used to inherit the arguments passed in another
  478. id declaration. This is useful when many files need to have the same defaults.
  479. .. code-block:: yaml
  480. /etc/foo.conf:
  481. file.managed:
  482. - source: salt://foo.conf
  483. - template: jinja
  484. - mkdirs: True
  485. - user: apache
  486. - group: apache
  487. - mode: 755
  488. /etc/bar.conf:
  489. file.managed:
  490. - source: salt://bar.conf
  491. - use:
  492. - file: /etc/foo.conf
  493. The ``use`` statement was developed primarily for the networking states but
  494. can be used on any states in Salt. This makes sense for the networking state
  495. because it can define a long list of options that need to be applied to
  496. multiple network interfaces.
  497. The ``use`` statement does not inherit the requisites arguments of the
  498. targeted state. This means also a chain of ``use`` requisites would not
  499. inherit inherited options.
  500. .. _requisites-in:
  501. .. _requisites-require-in:
  502. .. _requisites-watch-in:
  503. .. _requisites-onchanges-in:
  504. The _in version of requisites
  505. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  506. Direct requisites form a dependency in a single direction. This makes it possible
  507. for Salt to detect cyclical dependencies and helps prevent faulty logic. In some
  508. cases, often in loops, it is desirable to establish a dependency in the opposite
  509. direction.
  510. All direct requisites have an ``_in`` counterpart that behaves the same but forms
  511. the dependency in the opposite direction. The following sls examples will produce
  512. the exact same dependency mapping.
  513. .. code-block:: yaml
  514. httpd:
  515. pkg.installed: []
  516. service.running:
  517. - require:
  518. - pkg: httpd
  519. .. code-block:: yaml
  520. httpd:
  521. pkg.installed:
  522. - require_in:
  523. - service: httpd
  524. service.running: []
  525. In the following example, Salt will not try to manage the nginx service or any
  526. configuration files unless the nginx package is installed because of the ``pkg:
  527. nginx`` requisite.
  528. .. code-block:: yaml
  529. nginx:
  530. pkg.installed: []
  531. service.running:
  532. - enable: True
  533. - reload: True
  534. - require:
  535. - pkg: nginx
  536. php.sls
  537. .. code-block:: yaml
  538. include:
  539. - http
  540. php:
  541. pkg.installed:
  542. - require_in:
  543. - service: httpd
  544. mod_python.sls
  545. .. code-block:: yaml
  546. include:
  547. - http
  548. mod_python:
  549. pkg.installed:
  550. - require_in:
  551. - service: httpd
  552. Now the httpd server will only start if both php and mod_python are first verified to
  553. be installed. Thus allowing for a requisite to be defined "after the fact".
  554. .. code-block:: sls
  555. {% for cfile in salt.pillar.get('nginx:config_files') %}
  556. /etc/nginx/conf.d/{{ cfile }}:
  557. file.managed:
  558. - source: salt://nginx/configs/{{ cfile }}
  559. - require:
  560. - pkg: nginx
  561. - listen_in:
  562. - service: nginx
  563. {% endfor %}
  564. In this scenario, ``listen_in`` is a better choice than ``require_in`` because the
  565. ``listen`` requisite will trigger ``mod_wait`` behavior which will wait until the
  566. end of state execution and then reload the service.
  567. .. _requisites-any:
  568. .. _requisites-onchanges_any:
  569. .. _requisites-require_any:
  570. .. _requisites-onfail_any:
  571. The _any version of requisites
  572. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  573. .. versionadded:: 2018.3.0
  574. Some requisites have an ``_any`` counterpart that changes the requisite behavior
  575. from ``all()`` to ``any()``.
  576. .. code-block:: yaml
  577. A:
  578. cmd.run:
  579. - name: echo A
  580. - require_any:
  581. - cmd: B
  582. - cmd: C
  583. B:
  584. cmd.run:
  585. - name: echo B
  586. C:
  587. cmd.run:
  588. - name: /bin/false
  589. In this example `A` will run because at least one of the requirements specified,
  590. `B` or `C`, will succeed.
  591. .. code-block:: yaml
  592. myservice:
  593. pkg.installed
  594. /etc/myservice/myservice.conf:
  595. file.managed:
  596. - source: salt://myservice/files/myservice.conf
  597. /etc/yourservice/yourservice.conf:
  598. file.managed:
  599. - source: salt://yourservice/files/yourservice.conf
  600. /usr/local/sbin/myservice/post-changes-hook.sh
  601. cmd.run:
  602. - onchanges_any:
  603. - file: /etc/myservice/myservice.conf
  604. - file: /etc/your_service/yourservice.conf
  605. - require:
  606. - pkg: myservice
  607. In this example, `cmd.run` would be run only if either of the `file.managed`
  608. states generated changes and at least one of the watched state's "result" is
  609. ``True``.
  610. .. _requisites-fire-event:
  611. Altering States
  612. ---------------
  613. The state altering system is used to make sure that states are evaluated exactly
  614. as the user expects. It can be used to double check that a state preformed
  615. exactly how it was expected to, or to make 100% sure that a state only runs
  616. under certain conditions. The use of unless or onlyif options help make states
  617. even more stateful. The ``check_cmd`` option helps ensure that the result of a
  618. state is evaluated correctly.
  619. reload
  620. ~~~~~~
  621. ``reload_modules`` is a boolean option that forces salt to reload its modules
  622. after a state finishes. ``reload_pillar`` and ``reload_grains`` can also be set.
  623. See :ref:`Reloading Modules <reloading-modules>`.
  624. .. code-block:: yaml
  625. grains_refresh:
  626. module.run:
  627. - name: saltutil.refresh_grains
  628. - reload_grains: true
  629. grains_read:
  630. module.run:
  631. - name: grains.items
  632. .. _unless-requisite:
  633. unless
  634. ~~~~~~
  635. .. versionadded:: 2014.7.0
  636. The ``unless`` requisite specifies that a state should only run when any of
  637. the specified commands return ``False``. The ``unless`` requisite operates
  638. as NAND and is useful in giving more granular control over when a state should
  639. execute.
  640. **NOTE**: Under the hood ``unless`` calls ``cmd.retcode`` with
  641. ``python_shell=True``. This means the commands referenced by ``unless`` will be
  642. parsed by a shell, so beware of side-effects as this shell will be run with the
  643. same privileges as the salt-minion. Also be aware that the boolean value is
  644. determined by the shell's concept of ``True`` and ``False``, rather than Python's
  645. concept of ``True`` and ``False``.
  646. .. code-block:: yaml
  647. vim:
  648. pkg.installed:
  649. - unless:
  650. - rpm -q vim-enhanced
  651. - ls /usr/bin/vim
  652. In the example above, the state will only run if either the vim-enhanced
  653. package is not installed (returns ``False``) or if /usr/bin/vim does not
  654. exist (returns ``False``). The state will run if both commands return
  655. ``False``.
  656. However, the state will not run if both commands return ``True``.
  657. Unless checks are resolved for each name to which they are associated.
  658. For example:
  659. .. code-block:: yaml
  660. deploy_app:
  661. cmd.run:
  662. - names:
  663. - first_deploy_cmd
  664. - second_deploy_cmd
  665. - unless: some_check
  666. In the above case, ``some_check`` will be run prior to _each_ name -- once for
  667. ``first_deploy_cmd`` and a second time for ``second_deploy_cmd``.
  668. .. versionchanged:: 3000
  669. The ``unless`` requisite can take a module as a dictionary field in unless.
  670. The dictionary must contain an argument ``fun`` which is the module that is
  671. being run, and everything else must be passed in under the args key or will
  672. be passed as individual kwargs to the module function.
  673. .. code-block:: yaml
  674. install apache on debian based distros:
  675. cmd.run:
  676. - name: make install
  677. - cwd: /path/to/dir/whatever-2.1.5/
  678. - unless:
  679. - fun: file.file_exists
  680. path: /usr/local/bin/whatever
  681. .. code-block:: yaml
  682. set mysql root password:
  683. debconf.set:
  684. - name: mysql-server-5.7
  685. - data:
  686. 'mysql-server/root_password': {'type': 'password', 'value': {{pillar['mysql.pass']}} }
  687. - unless:
  688. - fun: pkg.version
  689. args:
  690. - mysql-server-5.7
  691. .. _onlyif-requisite:
  692. onlyif
  693. ~~~~~~
  694. .. versionadded:: 2014.7.0
  695. The ``onlyif`` requisite specifies that if each command listed in ``onlyif``
  696. returns ``True``, then the state is run. If any of the specified commands
  697. return ``False``, the state will not run.
  698. **NOTE**: Under the hood ``onlyif`` calls ``cmd.retcode`` with
  699. ``python_shell=True``. This means the commands referenced by ``onlyif`` will be
  700. parsed by a shell, so beware of side-effects as this shell will be run with the
  701. same privileges as the salt-minion. Also be aware that the boolean value is
  702. determined by the shell's concept of ``True`` and ``False``, rather than Python's
  703. concept of ``True`` and ``False``.
  704. .. code-block:: yaml
  705. stop-volume:
  706. module.run:
  707. - name: glusterfs.stop_volume
  708. - m_name: work
  709. - onlyif:
  710. - gluster volume status work
  711. - order: 1
  712. remove-volume:
  713. module.run:
  714. - name: glusterfs.delete
  715. - m_name: work
  716. - onlyif:
  717. - gluster volume info work
  718. - watch:
  719. - cmd: stop-volume
  720. The above example ensures that the stop_volume and delete modules only run
  721. if the gluster commands return a 0 ret value.
  722. .. versionchanged:: 3000
  723. The ``onlyif`` requisite can take a module as a dictionary field in onlyif.
  724. The dictionary must contain an argument ``fun`` which is the module that is
  725. being run, and everything else must be passed in under the args key or will
  726. be passed as individual kwargs to the module function.
  727. .. code-block:: yaml
  728. install apache on redhat based distros:
  729. pkg.latest:
  730. - name: httpd
  731. - onlyif:
  732. - fun: match.grain
  733. tgt: 'os_family: RedHat'
  734. install apache on debian based distros:
  735. pkg.latest:
  736. - name: apache2
  737. - onlyif:
  738. - fun: match.grain
  739. tgt: 'os_family: Debian'
  740. .. code-block:: yaml
  741. arbitrary file example:
  742. file.touch:
  743. - name: /path/to/file
  744. - onlyif:
  745. - fun: file.search
  746. args:
  747. - /etc/crontab
  748. - 'entry1'
  749. .. _creates-requisite:
  750. Creates
  751. -------
  752. .. versionadded:: Sodium
  753. The ``creates`` requisite specifies that a state should only run when any of
  754. the specified files do not already exist. Like ``unless``, ``creates`` requisite
  755. operates as NAND and is useful in giving more granular control over when a state
  756. should execute. This was previously used by the :mod:`cmd <salt.states.cmd>` and
  757. :mod:`docker_container <salt.states.docker_container>` states.
  758. .. code-block:: yaml
  759. contrived creates example:
  760. file.touch:
  761. - name: /path/to/file
  762. - creates: /path/to/file
  763. ``creates`` also accepts a list of files, in which case this state will
  764. run if **any** of the files do not exist:
  765. .. code-block:: yaml
  766. creates list:
  767. file.cmd:
  768. - name: /path/to/command
  769. - creates:
  770. - /path/file
  771. - /path/file2
  772. listen
  773. ~~~~~~
  774. .. versionadded:: 2017.7.0
  775. The ``runas`` global option is used to set the user which will be used to run
  776. the command in the ``cmd.run`` module.
  777. .. code-block:: yaml
  778. django:
  779. pip.installed:
  780. - name: django >= 1.6, <= 1.7
  781. - runas: daniel
  782. - require:
  783. - pkg: python-pip
  784. In the above state, the pip command run by ``cmd.run`` will be run by the daniel user.
  785. runas_password
  786. ~~~~~~~~~~~~~~
  787. .. versionadded:: 2017.7.2
  788. The ``runas_password`` global option is used to set the password used by the
  789. runas global option. This is required by ``cmd.run`` on Windows when ``runas``
  790. is specified. It will be set when ``runas_password`` is defined in the state.
  791. .. code-block:: yaml
  792. run_script:
  793. cmd.run:
  794. - name: Powershell -NonInteractive -ExecutionPolicy Bypass -File C:\\Temp\\script.ps1
  795. - runas: frank
  796. - runas_password: supersecret
  797. In the above state, the Powershell script run by ``cmd.run`` will be run by the
  798. frank user with the password ``supersecret``.
  799. check_cmd
  800. ~~~~~~~~~
  801. .. versionadded:: 2014.7.0
  802. Check Command is used for determining that a state did or did not run as
  803. expected.
  804. **NOTE**: Under the hood ``check_cmd`` calls ``cmd.retcode`` with
  805. ``python_shell=True``. This means the commands referenced by unless will be
  806. parsed by a shell, so beware of side-effects as this shell will be run with the
  807. same privileges as the salt-minion.
  808. .. code-block:: yaml
  809. comment-repo:
  810. file.replace:
  811. - name: /etc/yum.repos.d/fedora.repo
  812. - pattern: '^enabled=0'
  813. - repl: enabled=1
  814. - check_cmd:
  815. - "! grep 'enabled=0' /etc/yum.repos.d/fedora.repo"
  816. This will attempt to do a replace on all ``enabled=0`` in the .repo file, and
  817. replace them with ``enabled=1``. The ``check_cmd`` is just a bash command. It
  818. will do a grep for ``enabled=0`` in the file, and if it finds any, it will
  819. return a 0, which will be inverted by the leading ``!``, causing ``check_cmd``
  820. to set the state as failed. If it returns a 1, meaning it didn't find any
  821. ``enabled=0``, it will be inverted by the leading ``!``, returning a 0, and
  822. declaring the function succeeded.
  823. **NOTE**: This requisite ``check_cmd`` functions differently than the ``check_cmd``
  824. of the ``file.managed`` state.
  825. Overriding Checks
  826. ~~~~~~~~~~~~~~~~~
  827. There are two commands used for the above checks.
  828. ``mod_run_check`` is used to check for ``onlyif`` and ``unless``. If the goal is to
  829. override the global check for these to variables, include a ``mod_run_check`` in the
  830. salt/states/ file.
  831. ``mod_run_check_cmd`` is used to check for the check_cmd options. To override
  832. this one, include a ``mod_run_check_cmd`` in the states file for the state.
  833. Fire Event Notifications
  834. ========================
  835. .. versionadded:: 2015.8.0
  836. The `fire_event` option in a state will cause the minion to send an event to
  837. the Salt Master upon completion of that individual state.
  838. The following example will cause the minion to send an event to the Salt Master
  839. with a tag of `salt/state_result/20150505121517276431/dasalt/nano` and the
  840. result of the state will be the data field of the event. Notice that the `name`
  841. of the state gets added to the tag.
  842. .. code-block:: yaml
  843. nano_stuff:
  844. pkg.installed:
  845. - name: nano
  846. - fire_event: True
  847. In the following example instead of setting `fire_event` to `True`,
  848. `fire_event` is set to an arbitrary string, which will cause the event to be
  849. sent with this tag:
  850. `salt/state_result/20150505121725642845/dasalt/custom/tag/nano/finished`
  851. .. code-block:: yaml
  852. nano_stuff:
  853. pkg.installed:
  854. - name: nano
  855. - fire_event: custom/tag/nano/finished
  856. Retrying States
  857. ===============
  858. .. versionadded:: 2017.7.0
  859. The retry option in a state allows it to be executed multiple times until a desired
  860. result is obtained or the maximum number of attempts have been made.
  861. The retry option can be configured by the ``attempts``, ``until``, ``interval``, and
  862. ``splay`` parameters.
  863. The ``attempts`` parameter controls the maximum number of times the state will be
  864. run. If not specified or if an invalid value is specified, ``attempts`` will default
  865. to ``2``.
  866. The ``until`` parameter defines the result that is required to stop retrying the state.
  867. If not specified or if an invalid value is specified, ``until`` will default to ``True``
  868. The ``interval`` parameter defines the amount of time, in seconds, that the system
  869. will wait between attempts. If not specified or if an invalid value is specified,
  870. ``interval`` will default to ``30``.
  871. The ``splay`` parameter allows the ``interval`` to be additionally spread out. If not
  872. specified or if an invalid value is specified, ``splay`` defaults to ``0`` (i.e. no
  873. splaying will occur).
  874. The following example will run the pkg.installed state until it returns ``True`` or it has
  875. been run ``5`` times. Each attempt will be ``60`` seconds apart and the interval will be splayed
  876. up to an additional ``10`` seconds:
  877. .. code-block:: yaml
  878. my_retried_state:
  879. pkg.installed:
  880. - name: nano
  881. - retry:
  882. attempts: 5
  883. until: True
  884. interval: 60
  885. splay: 10
  886. The following example will run the pkg.installed state with all the defaults for ``retry``.
  887. The state will run up to ``2`` times, each attempt being ``30`` seconds apart, or until it
  888. returns ``True``.
  889. .. code-block:: yaml
  890. install_nano:
  891. pkg.installed:
  892. - name: nano
  893. - retry: True
  894. The following example will run the file.exists state every ``30`` seconds up to ``15`` times
  895. or until the file exists (i.e. the state returns ``True``).
  896. .. code-block:: yaml
  897. wait_for_file:
  898. file.exists:
  899. - name: /path/to/file
  900. - retry:
  901. attempts: 15
  902. interval: 30
  903. Return data from a retried state
  904. --------------------------------
  905. When a state is retried, the returned output is as follows:
  906. The ``result`` return value is the ``result`` from the final run. For example, imagine a state set
  907. to ``retry`` up to three times or ``until`` ``True``. If the state returns ``False`` on the first run
  908. and then ``True`` on the second, the ``result`` of the state will be ``True``.
  909. The ``started`` return value is the ``started`` from the first run.
  910. The ``duration`` return value is the total duration of all attempts plus the retry intervals.
  911. The ``comment`` return value will include the result and comment from all previous attempts.
  912. For example:
  913. .. code-block:: yaml
  914. wait_for_file:
  915. file.exists:
  916. - name: /path/to/file
  917. - retry:
  918. attempts: 10
  919. interval: 2
  920. splay: 5
  921. Would return similar to the following. The state result in this case is ``False`` (file.exist was run 10
  922. times with a 2 second interval, but the file specified did not exist on any run).
  923. .. code-block:: none
  924. ID: wait_for_file
  925. Function: file.exists
  926. Result: False
  927. Comment: Attempt 1: Returned a result of "False", with the following comment: "Specified path /path/to/file does not exist"
  928. Attempt 2: Returned a result of "False", with the following comment: "Specified path /path/to/file does not exist"
  929. Attempt 3: Returned a result of "False", with the following comment: "Specified path /path/to/file does not exist"
  930. Attempt 4: Returned a result of "False", with the following comment: "Specified path /path/to/file does not exist"
  931. Attempt 5: Returned a result of "False", with the following comment: "Specified path /path/to/file does not exist"
  932. Attempt 6: Returned a result of "False", with the following comment: "Specified path /path/to/file does not exist"
  933. Attempt 7: Returned a result of "False", with the following comment: "Specified path /path/to/file does not exist"
  934. Attempt 8: Returned a result of "False", with the following comment: "Specified path /path/to/file does not exist"
  935. Attempt 9: Returned a result of "False", with the following comment: "Specified path /path/to/file does not exist"
  936. Specified path /path/to/file does not exist
  937. Started: 09:08:12.903000
  938. Duration: 47000.0 ms
  939. Changes: