requisites.rst 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223
  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 `<requisite>_in <requisites-in>` form:
  125. * `require <requisites-require>`: Requires that a list of target states succeed before execution
  126. * `onchanges <requisites-onchanges>`: Execute if any target states succeed with changes
  127. * `watch <requisites-watch>`: Similar to ``onchanges``; modifies state behavior using ``mod_watch``
  128. * `listen <requisites-listen>`: Similar to ``onchanges``; delays execution to end of state run using ``mod_wait``
  129. * `prereq <requisites-prereq>`: Execute prior to target state if target state expects to produce changes
  130. * `onfail <requisites-onfail>`: Execute only if a target state fails
  131. * `use <requisites-use>`: Copy arguments from another state
  132. Several requisite types have a corresponding `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 `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. listen
  750. ~~~~~~
  751. .. versionadded:: 2017.7.0
  752. The ``runas`` global option is used to set the user which will be used to run
  753. the command in the ``cmd.run`` module.
  754. .. code-block:: yaml
  755. django:
  756. pip.installed:
  757. - name: django >= 1.6, <= 1.7
  758. - runas: daniel
  759. - require:
  760. - pkg: python-pip
  761. In the above state, the pip command run by ``cmd.run`` will be run by the daniel user.
  762. runas_password
  763. ~~~~~~~~~~~~~~
  764. .. versionadded:: 2017.7.2
  765. The ``runas_password`` global option is used to set the password used by the
  766. runas global option. This is required by ``cmd.run`` on Windows when ``runas``
  767. is specified. It will be set when ``runas_password`` is defined in the state.
  768. .. code-block:: yaml
  769. run_script:
  770. cmd.run:
  771. - name: Powershell -NonInteractive -ExecutionPolicy Bypass -File C:\\Temp\\script.ps1
  772. - runas: frank
  773. - runas_password: supersecret
  774. In the above state, the Powershell script run by ``cmd.run`` will be run by the
  775. frank user with the password ``supersecret``.
  776. check_cmd
  777. ~~~~~~~~~
  778. .. versionadded:: 2014.7.0
  779. Check Command is used for determining that a state did or did not run as
  780. expected.
  781. **NOTE**: Under the hood ``check_cmd`` calls ``cmd.retcode`` with
  782. ``python_shell=True``. This means the commands referenced by unless will be
  783. parsed by a shell, so beware of side-effects as this shell will be run with the
  784. same privileges as the salt-minion.
  785. .. code-block:: yaml
  786. comment-repo:
  787. file.replace:
  788. - name: /etc/yum.repos.d/fedora.repo
  789. - pattern: '^enabled=0'
  790. - repl: enabled=1
  791. - check_cmd:
  792. - "! grep 'enabled=0' /etc/yum.repos.d/fedora.repo"
  793. This will attempt to do a replace on all ``enabled=0`` in the .repo file, and
  794. replace them with ``enabled=1``. The ``check_cmd`` is just a bash command. It
  795. will do a grep for ``enabled=0`` in the file, and if it finds any, it will
  796. return a 0, which will be inverted by the leading ``!``, causing ``check_cmd``
  797. to set the state as failed. If it returns a 1, meaning it didn't find any
  798. ``enabled=0``, it will be inverted by the leading ``!``, returning a 0, and
  799. declaring the function succeeded.
  800. **NOTE**: This requisite ``check_cmd`` functions differently than the ``check_cmd``
  801. of the ``file.managed`` state.
  802. Overriding Checks
  803. ~~~~~~~~~~~~~~~~~
  804. There are two commands used for the above checks.
  805. ``mod_run_check`` is used to check for ``onlyif`` and ``unless``. If the goal is to
  806. override the global check for these to variables, include a ``mod_run_check`` in the
  807. salt/states/ file.
  808. ``mod_run_check_cmd`` is used to check for the check_cmd options. To override
  809. this one, include a ``mod_run_check_cmd`` in the states file for the state.
  810. Fire Event Notifications
  811. ========================
  812. .. versionadded:: 2015.8.0
  813. The `fire_event` option in a state will cause the minion to send an event to
  814. the Salt Master upon completion of that individual state.
  815. The following example will cause the minion to send an event to the Salt Master
  816. with a tag of `salt/state_result/20150505121517276431/dasalt/nano` and the
  817. result of the state will be the data field of the event. Notice that the `name`
  818. of the state gets added to the tag.
  819. .. code-block:: yaml
  820. nano_stuff:
  821. pkg.installed:
  822. - name: nano
  823. - fire_event: True
  824. In the following example instead of setting `fire_event` to `True`,
  825. `fire_event` is set to an arbitrary string, which will cause the event to be
  826. sent with this tag:
  827. `salt/state_result/20150505121725642845/dasalt/custom/tag/nano/finished`
  828. .. code-block:: yaml
  829. nano_stuff:
  830. pkg.installed:
  831. - name: nano
  832. - fire_event: custom/tag/nano/finished
  833. Retrying States
  834. ===============
  835. .. versionadded:: 2017.7.0
  836. The retry option in a state allows it to be executed multiple times until a desired
  837. result is obtained or the maximum number of attempts have been made.
  838. The retry option can be configured by the ``attempts``, ``until``, ``interval``, and
  839. ``splay`` parameters.
  840. The ``attempts`` parameter controls the maximum number of times the state will be
  841. run. If not specified or if an invalid value is specified, ``attempts`` will default
  842. to ``2``.
  843. The ``until`` parameter defines the result that is required to stop retrying the state.
  844. If not specified or if an invalid value is specified, ``until`` will default to ``True``
  845. The ``interval`` parameter defines the amount of time, in seconds, that the system
  846. will wait between attempts. If not specified or if an invalid value is specified,
  847. ``interval`` will default to ``30``.
  848. The ``splay`` parameter allows the ``interval`` to be additionally spread out. If not
  849. specified or if an invalid value is specified, ``splay`` defaults to ``0`` (i.e. no
  850. splaying will occur).
  851. The following example will run the pkg.installed state until it returns ``True`` or it has
  852. been run ``5`` times. Each attempt will be ``60`` seconds apart and the interval will be splayed
  853. up to an additional ``10`` seconds:
  854. .. code-block:: yaml
  855. my_retried_state:
  856. pkg.installed:
  857. - name: nano
  858. - retry:
  859. attempts: 5
  860. until: True
  861. interval: 60
  862. splay: 10
  863. The following example will run the pkg.installed state with all the defaults for ``retry``.
  864. The state will run up to ``2`` times, each attempt being ``30`` seconds apart, or until it
  865. returns ``True``.
  866. .. code-block:: yaml
  867. install_nano:
  868. pkg.installed:
  869. - name: nano
  870. - retry: True
  871. The following example will run the file.exists state every ``30`` seconds up to ``15`` times
  872. or until the file exists (i.e. the state returns ``True``).
  873. .. code-block:: yaml
  874. wait_for_file:
  875. file.exists:
  876. - name: /path/to/file
  877. - retry:
  878. attempts: 15
  879. interval: 30
  880. Return data from a retried state
  881. --------------------------------
  882. When a state is retried, the returned output is as follows:
  883. The ``result`` return value is the ``result`` from the final run. For example, imagine a state set
  884. to ``retry`` up to three times or ``until`` ``True``. If the state returns ``False`` on the first run
  885. and then ``True`` on the second, the ``result`` of the state will be ``True``.
  886. The ``started`` return value is the ``started`` from the first run.
  887. The ``duration`` return value is the total duration of all attempts plus the retry intervals.
  888. The ``comment`` return value will include the result and comment from all previous attempts.
  889. For example:
  890. .. code-block:: yaml
  891. wait_for_file:
  892. file.exists:
  893. - name: /path/to/file
  894. - retry:
  895. attempts: 10
  896. interval: 2
  897. splay: 5
  898. Would return similar to the following. The state result in this case is ``False`` (file.exist was run 10
  899. times with a 2 second interval, but the file specified did not exist on any run).
  900. .. code-block:: none
  901. ID: wait_for_file
  902. Function: file.exists
  903. Result: False
  904. Comment: Attempt 1: Returned a result of "False", with the following comment: "Specified path /path/to/file does not exist"
  905. Attempt 2: Returned a result of "False", with the following comment: "Specified path /path/to/file does not exist"
  906. Attempt 3: Returned a result of "False", with the following comment: "Specified path /path/to/file does not exist"
  907. Attempt 4: Returned a result of "False", with the following comment: "Specified path /path/to/file does not exist"
  908. Attempt 5: Returned a result of "False", with the following comment: "Specified path /path/to/file does not exist"
  909. Attempt 6: Returned a result of "False", with the following comment: "Specified path /path/to/file does not exist"
  910. Attempt 7: Returned a result of "False", with the following comment: "Specified path /path/to/file does not exist"
  911. Attempt 8: Returned a result of "False", with the following comment: "Specified path /path/to/file does not exist"
  912. Attempt 9: Returned a result of "False", with the following comment: "Specified path /path/to/file does not exist"
  913. Specified path /path/to/file does not exist
  914. Started: 09:08:12.903000
  915. Duration: 47000.0 ms
  916. Changes: