requisites.rst 37 KB

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