1
0

requisites.rst 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289
  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. .. code-block:: json
  272. {
  273. "local": {
  274. "pkgrepo_|-salt-minion_|-salt-minion_|-managed": {
  275. "comment": "Package repo 'salt-minion' already configured",
  276. "__run_num__": 0,
  277. "changes": {},
  278. "name": "salt-minion",
  279. "result": true
  280. }
  281. }
  282. }
  283. If the "result" of the watched state is ``True``, the watching state *will
  284. execute normally*, and if it is ``False``, the watching state will never run.
  285. This part of ``watch`` mirrors the functionality of the ``require`` requisite.
  286. If the "result" of the watched state is ``True`` *and* the "changes"
  287. key contains a populated dictionary (changes occurred in the watched state),
  288. then the ``watch`` requisite can add additional behavior. This additional
  289. behavior is defined by the ``mod_watch`` function within the watching state
  290. module. If the ``mod_watch`` function exists in the watching state module, it
  291. will be called *in addition to* the normal watching state. The return data
  292. from the ``mod_watch`` function is what will be returned to the master in this
  293. case; the return data from the main watching function is discarded.
  294. If the "changes" key contains an empty dictionary, the ``watch`` requisite acts
  295. exactly like the ``require`` requisite (the watching state will execute if
  296. "result" is ``True``, and fail if "result" is ``False`` in the watched state).
  297. .. note::
  298. If the watching state ``changes`` key contains values, then ``mod_watch``
  299. will not be called. If you're using ``watch`` or ``watch_in`` then it's a
  300. good idea to have a state that only enforces one attribute - such as
  301. splitting out ``service.running`` into its own state and have
  302. ``service.enabled`` in another.
  303. One common source of confusion is expecting ``mod_watch`` to be called for
  304. every necessary change. You might be tempted to write something like this:
  305. .. code-block:: yaml
  306. httpd:
  307. service.running:
  308. - enable: True
  309. - watch:
  310. - file: httpd-config
  311. httpd-config:
  312. file.managed:
  313. - name: /etc/httpd/conf/httpd.conf
  314. - source: salt://httpd/files/apache.conf
  315. If your service is already running but not enabled, you might expect that Salt
  316. will be able to tell that since the config file changed your service needs to
  317. be restarted. This is not the case. Because the service needs to be enabled,
  318. that change will be made and ``mod_watch`` will never be triggered. In this
  319. case, changes to your ``apache.conf`` will fail to be loaded. If you want to
  320. ensure that your service always reloads the correct way to handle this is
  321. either ensure that your service is not running before applying your state, or
  322. simply make sure that ``service.running`` is in a state on its own:
  323. .. code-block:: yaml
  324. enable-httpd:
  325. service.enabled:
  326. - name: httpd
  327. start-httpd:
  328. service.running:
  329. - name: httpd
  330. - watch:
  331. - file: httpd-config
  332. httpd-config:
  333. file.managed:
  334. - name: /etc/httpd/conf/httpd.conf
  335. - source: salt://httpd/files/apache.conf
  336. Now that ``service.running`` is its own state, changes to ``service.enabled``
  337. will no longer prevent ``mod_watch`` from getting triggered, so your ``httpd``
  338. service will get restarted like you want.
  339. .. _requisites-listen:
  340. listen
  341. ~~~~~~
  342. .. versionadded:: 2014.7.0
  343. A ``listen`` requisite is used to trigger the ``mod_wait`` function of an
  344. execution module. Rather than modifying execution order, the ``mod_wait`` state
  345. created by ``listen`` will execute at the end of the state run.
  346. .. code-block:: yaml
  347. restart-apache2:
  348. service.running:
  349. - name: apache2
  350. - listen:
  351. - file: /etc/apache2/apache2.conf
  352. configure-apache2:
  353. file.managed:
  354. - name: /etc/apache2/apache2.conf
  355. - source: salt://apache2/apache2.conf
  356. This example will cause apache2 to restart when the apache2.conf file is
  357. changed, but the apache2 restart will happen at the end of the state run.
  358. .. code-block:: yaml
  359. restart-apache2:
  360. service.running:
  361. - name: apache2
  362. configure-apache2:
  363. file.managed:
  364. - name: /etc/apache2/apache2.conf
  365. - source: salt://apache2/apache2.conf
  366. - listen_in:
  367. - service: apache2
  368. This example does the same as the above example, but puts the state argument
  369. on the file resource, rather than the service resource.
  370. .. _requisites-prereq:
  371. prereq
  372. ~~~~~~
  373. .. versionadded:: 0.16.0
  374. The ``prereq`` requisite works similar to ``onchanges`` except that it uses the
  375. result from ``test=True`` on the observed state to determine if it should run
  376. prior to the observed state being run.
  377. The best way to define how ``prereq`` operates is displayed in the following
  378. practical example: When a service should be shut down because underlying code
  379. is going to change, the service should be off-line while the update occurs. In
  380. this example, ``graceful-down`` is the pre-requiring state and ``site-code``
  381. is the pre-required state.
  382. .. code-block:: yaml
  383. graceful-down:
  384. cmd.run:
  385. - name: service apache graceful
  386. - prereq:
  387. - file: site-code
  388. site-code:
  389. file.recurse:
  390. - name: /opt/site_code
  391. - source: salt://site/code
  392. In this case, the apache server will only be shut down if the site-code state
  393. expects to deploy fresh code via the file.recurse call. The site-code deployment
  394. will only be executed if the graceful-down run completes successfully.
  395. When a ``prereq`` requisite is evaluated, the pre-required state reports if it
  396. expects to have any changes. It does this by running the pre-required single
  397. state as a test-run by enabling ``test=True``. This test-run will return a
  398. dictionary containing a key named "changes". (See the ``watch`` section above
  399. for examples of "changes" dictionaries.)
  400. If the "changes" key contains a populated dictionary, it means that the
  401. pre-required state expects changes to occur when the state is actually
  402. executed, as opposed to the test-run. The pre-requiring state will now
  403. run. If the pre-requiring state executes successfully, the pre-required
  404. state will then execute. If the pre-requiring state fails, the pre-required
  405. state will not execute.
  406. If the "changes" key contains an empty dictionary, this means that changes are
  407. not expected by the pre-required state. Neither the pre-required state nor the
  408. pre-requiring state will run.
  409. .. _requisites-onfail:
  410. onfail
  411. ~~~~~~
  412. .. versionadded:: 2014.7.0
  413. The ``onfail`` requisite allows for reactions to happen strictly as a response
  414. to the failure of another state. This can be used in a number of ways, such as
  415. sending a notification or attempting an alternate task or thread of tasks when
  416. an important state fails.
  417. The ``onfail`` requisite is applied in the same way as ``require`` and ``watch``:
  418. .. code-block:: yaml
  419. primary_mount:
  420. mount.mounted:
  421. - name: /mnt/share
  422. - device: 10.0.0.45:/share
  423. - fstype: nfs
  424. backup_mount:
  425. mount.mounted:
  426. - name: /mnt/share
  427. - device: 192.168.40.34:/share
  428. - fstype: nfs
  429. - onfail:
  430. - mount: primary_mount
  431. .. code-block:: yaml
  432. build_site:
  433. cmd.run:
  434. - name: /srv/web/app/build_site
  435. notify-build_failure:
  436. hipchat.send_message:
  437. - room_id: 123456
  438. - message: "Building website fail on {{ salt.grains.get('id') }}"
  439. The default behavior of the ``onfail`` when multiple requisites are listed is
  440. the opposite of other requisites in the salt state engine, it acts by default
  441. like ``any()`` instead of ``all()``. This means that when you list multiple
  442. onfail requisites on a state, if *any* fail the requisite will be satisfied.
  443. If you instead need *all* logic to be applied, you can use ``onfail_all``
  444. form:
  445. .. code-block:: yaml
  446. test_site_a:
  447. cmd.run:
  448. - name: ping -c1 10.0.0.1
  449. test_site_b:
  450. cmd.run:
  451. - name: ping -c1 10.0.0.2
  452. notify_site_down:
  453. hipchat.send_message:
  454. - room_id: 123456
  455. - message: "Both primary and backup sites are down!"
  456. - onfail_all:
  457. - cmd: test_site_a
  458. - cmd: test_site_b
  459. In this contrived example `notify_site_down` will run when both 10.0.0.1 and
  460. 10.0.0.2 fail to respond to ping.
  461. .. note::
  462. Setting failhard (:ref:`globally <global-failhard>` or in
  463. :ref:`the failing state <state-level-failhard>`) to ``True`` will cause
  464. ``onfail``, ``onfail_in`` and ``onfail_any`` requisites to be ignored.
  465. If you want to combine a global failhard set to True with ``onfail``,
  466. ``onfail_in`` or ``onfail_any``, you will have to explicitly set failhard
  467. to ``False`` (overriding the global setting) in the state that could fail.
  468. .. note::
  469. Beginning in the ``2016.11.0`` release of Salt, ``onfail`` uses OR logic for
  470. multiple listed ``onfail`` requisites. Prior to the ``2016.11.0`` release,
  471. ``onfail`` used AND logic. See `Issue #22370`_ for more information.
  472. Beginning in the ``Neon`` release of Salt, a new ``onfail_all`` requisite
  473. form is available if AND logic is desired.
  474. .. _Issue #22370: https://github.com/saltstack/salt/issues/22370
  475. .. _requisites-use:
  476. use
  477. ~~~
  478. The ``use`` requisite is used to inherit the arguments passed in another
  479. id declaration. This is useful when many files need to have the same defaults.
  480. .. code-block:: yaml
  481. /etc/foo.conf:
  482. file.managed:
  483. - source: salt://foo.conf
  484. - template: jinja
  485. - mkdirs: True
  486. - user: apache
  487. - group: apache
  488. - mode: 755
  489. /etc/bar.conf:
  490. file.managed:
  491. - source: salt://bar.conf
  492. - use:
  493. - file: /etc/foo.conf
  494. The ``use`` statement was developed primarily for the networking states but
  495. can be used on any states in Salt. This makes sense for the networking state
  496. because it can define a long list of options that need to be applied to
  497. multiple network interfaces.
  498. The ``use`` statement does not inherit the requisites arguments of the
  499. targeted state. This means also a chain of ``use`` requisites would not
  500. inherit inherited options.
  501. .. _requisites-in:
  502. .. _requisites-require-in:
  503. .. _requisites-watch-in:
  504. .. _requisites-onchanges-in:
  505. The _in version of requisites
  506. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  507. Direct requisites form a dependency in a single direction. This makes it possible
  508. for Salt to detect cyclical dependencies and helps prevent faulty logic. In some
  509. cases, often in loops, it is desirable to establish a dependency in the opposite
  510. direction.
  511. All direct requisites have an ``_in`` counterpart that behaves the same but forms
  512. the dependency in the opposite direction. The following sls examples will produce
  513. the exact same dependency mapping.
  514. .. code-block:: yaml
  515. httpd:
  516. pkg.installed: []
  517. service.running:
  518. - require:
  519. - pkg: httpd
  520. .. code-block:: yaml
  521. httpd:
  522. pkg.installed:
  523. - require_in:
  524. - service: httpd
  525. service.running: []
  526. In the following example, Salt will not try to manage the nginx service or any
  527. configuration files unless the nginx package is installed because of the ``pkg:
  528. nginx`` requisite.
  529. .. code-block:: yaml
  530. nginx:
  531. pkg.installed: []
  532. service.running:
  533. - enable: True
  534. - reload: True
  535. - require:
  536. - pkg: nginx
  537. php.sls
  538. .. code-block:: yaml
  539. include:
  540. - http
  541. php:
  542. pkg.installed:
  543. - require_in:
  544. - service: httpd
  545. mod_python.sls
  546. .. code-block:: yaml
  547. include:
  548. - http
  549. mod_python:
  550. pkg.installed:
  551. - require_in:
  552. - service: httpd
  553. Now the httpd server will only start if both php and mod_python are first verified to
  554. be installed. Thus allowing for a requisite to be defined "after the fact".
  555. .. code-block:: sls
  556. {% for cfile in salt.pillar.get('nginx:config_files') %}
  557. /etc/nginx/conf.d/{{ cfile }}:
  558. file.managed:
  559. - source: salt://nginx/configs/{{ cfile }}
  560. - require:
  561. - pkg: nginx
  562. - listen_in:
  563. - service: nginx
  564. {% endfor %}
  565. In this scenario, ``listen_in`` is a better choice than ``require_in`` because the
  566. ``listen`` requisite will trigger ``mod_wait`` behavior which will wait until the
  567. end of state execution and then reload the service.
  568. .. _requisites-any:
  569. .. _requisites-onchanges_any:
  570. .. _requisites-require_any:
  571. .. _requisites-onfail_any:
  572. The _any version of requisites
  573. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  574. .. versionadded:: 2018.3.0
  575. Some requisites have an ``_any`` counterpart that changes the requisite behavior
  576. from ``all()`` to ``any()``.
  577. .. code-block:: yaml
  578. A:
  579. cmd.run:
  580. - name: echo A
  581. - require_any:
  582. - cmd: B
  583. - cmd: C
  584. B:
  585. cmd.run:
  586. - name: echo B
  587. C:
  588. cmd.run:
  589. - name: /bin/false
  590. In this example `A` will run because at least one of the requirements specified,
  591. `B` or `C`, will succeed.
  592. .. code-block:: yaml
  593. myservice:
  594. pkg.installed
  595. /etc/myservice/myservice.conf:
  596. file.managed:
  597. - source: salt://myservice/files/myservice.conf
  598. /etc/yourservice/yourservice.conf:
  599. file.managed:
  600. - source: salt://yourservice/files/yourservice.conf
  601. /usr/local/sbin/myservice/post-changes-hook.sh
  602. cmd.run:
  603. - onchanges_any:
  604. - file: /etc/myservice/myservice.conf
  605. - file: /etc/your_service/yourservice.conf
  606. - require:
  607. - pkg: myservice
  608. In this example, `cmd.run` would be run only if either of the `file.managed`
  609. states generated changes and at least one of the watched state's "result" is
  610. ``True``.
  611. .. _requisites-fire-event:
  612. Altering States
  613. ---------------
  614. The state altering system is used to make sure that states are evaluated exactly
  615. as the user expects. It can be used to double check that a state preformed
  616. exactly how it was expected to, or to make 100% sure that a state only runs
  617. under certain conditions. The use of unless or onlyif options help make states
  618. even more stateful. The ``check_cmd`` option helps ensure that the result of a
  619. state is evaluated correctly.
  620. reload
  621. ~~~~~~
  622. ``reload_modules`` is a boolean option that forces salt to reload its modules
  623. after a state finishes. ``reload_pillar`` and ``reload_grains`` can also be set.
  624. See :ref:`Reloading Modules <reloading-modules>`.
  625. .. code-block:: yaml
  626. grains_refresh:
  627. module.run:
  628. - name: saltutil.refresh_grains
  629. - reload_grains: true
  630. grains_read:
  631. module.run:
  632. - name: grains.items
  633. .. _unless-requisite:
  634. unless
  635. ~~~~~~
  636. .. versionadded:: 2014.7.0
  637. The ``unless`` requisite specifies that a state should only run when any of
  638. the specified commands return ``False``. The ``unless`` requisite operates
  639. as NAND and is useful in giving more granular control over when a state should
  640. execute.
  641. **NOTE**: Under the hood ``unless`` calls ``cmd.retcode`` with
  642. ``python_shell=True``. This means the commands referenced by ``unless`` will be
  643. parsed by a shell, so beware of side-effects as this shell will be run with the
  644. same privileges as the salt-minion. Also be aware that the boolean value is
  645. determined by the shell's concept of ``True`` and ``False``, rather than Python's
  646. concept of ``True`` and ``False``.
  647. .. code-block:: yaml
  648. vim:
  649. pkg.installed:
  650. - unless:
  651. - rpm -q vim-enhanced
  652. - ls /usr/bin/vim
  653. In the example above, the state will only run if either the vim-enhanced
  654. package is not installed (returns ``False``) or if /usr/bin/vim does not
  655. exist (returns ``False``). The state will run if both commands return
  656. ``False``.
  657. However, the state will not run if both commands return ``True``.
  658. Unless checks are resolved for each name to which they are associated.
  659. For example:
  660. .. code-block:: yaml
  661. deploy_app:
  662. cmd.run:
  663. - names:
  664. - first_deploy_cmd
  665. - second_deploy_cmd
  666. - unless: some_check
  667. In the above case, ``some_check`` will be run prior to _each_ name -- once for
  668. ``first_deploy_cmd`` and a second time for ``second_deploy_cmd``.
  669. .. versionchanged:: 3000
  670. The ``unless`` requisite can take a module as a dictionary field in unless.
  671. The dictionary must contain an argument ``fun`` which is the module that is
  672. being run, and everything else must be passed in under the args key or will
  673. be passed as individual kwargs to the module function.
  674. .. code-block:: yaml
  675. install apache on debian based distros:
  676. cmd.run:
  677. - name: make install
  678. - cwd: /path/to/dir/whatever-2.1.5/
  679. - unless:
  680. - fun: file.file_exists
  681. path: /usr/local/bin/whatever
  682. .. code-block:: yaml
  683. set mysql root password:
  684. debconf.set:
  685. - name: mysql-server-5.7
  686. - data:
  687. 'mysql-server/root_password': {'type': 'password', 'value': {{pillar['mysql.pass']}} }
  688. - unless:
  689. - fun: pkg.version
  690. args:
  691. - mysql-server-5.7
  692. .. versionchanged:: sodium
  693. For modules which return a deeper data structure, the ``get_return`` key can
  694. be used to access results.
  695. .. code-block:: yaml
  696. test:
  697. test.nop:
  698. - name: foo
  699. - unless:
  700. - fun: consul.get
  701. consul_url: http://127.0.0.1:8500
  702. key: not-existing
  703. get_return: res
  704. .. _onlyif-requisite:
  705. onlyif
  706. ~~~~~~
  707. .. versionadded:: 2014.7.0
  708. The ``onlyif`` requisite specifies that if each command listed in ``onlyif``
  709. returns ``True``, then the state is run. If any of the specified commands
  710. return ``False``, the state will not run.
  711. **NOTE**: Under the hood ``onlyif`` calls ``cmd.retcode`` with
  712. ``python_shell=True``. This means the commands referenced by ``onlyif`` will be
  713. parsed by a shell, so beware of side-effects as this shell will be run with the
  714. same privileges as the salt-minion. Also be aware that the boolean value is
  715. determined by the shell's concept of ``True`` and ``False``, rather than Python's
  716. concept of ``True`` and ``False``.
  717. .. code-block:: yaml
  718. stop-volume:
  719. module.run:
  720. - name: glusterfs.stop_volume
  721. - m_name: work
  722. - onlyif:
  723. - gluster volume status work
  724. - order: 1
  725. remove-volume:
  726. module.run:
  727. - name: glusterfs.delete
  728. - m_name: work
  729. - onlyif:
  730. - gluster volume info work
  731. - watch:
  732. - cmd: stop-volume
  733. The above example ensures that the stop_volume and delete modules only run
  734. if the gluster commands return a 0 ret value.
  735. .. versionchanged:: 3000
  736. The ``onlyif`` requisite can take a module as a dictionary field in onlyif.
  737. The dictionary must contain an argument ``fun`` which is the module that is
  738. being run, and everything else must be passed in under the args key or will
  739. be passed as individual kwargs to the module function.
  740. .. code-block:: yaml
  741. install apache on redhat based distros:
  742. pkg.latest:
  743. - name: httpd
  744. - onlyif:
  745. - fun: match.grain
  746. tgt: 'os_family:RedHat'
  747. install apache on debian based distros:
  748. pkg.latest:
  749. - name: apache2
  750. - onlyif:
  751. - fun: match.grain
  752. tgt: 'os_family:Debian'
  753. .. code-block:: yaml
  754. arbitrary file example:
  755. file.touch:
  756. - name: /path/to/file
  757. - onlyif:
  758. - fun: file.search
  759. args:
  760. - /etc/crontab
  761. - 'entry1'
  762. .. versionchanged:: sodium
  763. For modules which return a deeper data structure, the ``get_return`` key can
  764. be used to access results.
  765. .. code-block:: yaml
  766. test:
  767. test.nop:
  768. - name: foo
  769. - onlyif:
  770. - fun: consul.get
  771. consul_url: http://127.0.0.1:8500
  772. key: does-exist
  773. get_return: res
  774. .. _creates-requisite:
  775. Creates
  776. -------
  777. .. versionadded:: 3001
  778. The ``creates`` requisite specifies that a state should only run when any of
  779. the specified files do not already exist. Like ``unless``, ``creates`` requisite
  780. operates as NAND and is useful in giving more granular control over when a state
  781. should execute. This was previously used by the :mod:`cmd <salt.states.cmd>` and
  782. :mod:`docker_container <salt.states.docker_container>` states.
  783. .. code-block:: yaml
  784. contrived creates example:
  785. file.touch:
  786. - name: /path/to/file
  787. - creates: /path/to/file
  788. ``creates`` also accepts a list of files, in which case this state will
  789. run if **any** of the files do not exist:
  790. .. code-block:: yaml
  791. creates list:
  792. file.cmd:
  793. - name: /path/to/command
  794. - creates:
  795. - /path/file
  796. - /path/file2
  797. runas
  798. ~~~~~
  799. .. versionadded:: 2017.7.0
  800. The ``runas`` global option is used to set the user which will be used to run
  801. the command in the ``cmd.run`` module.
  802. .. code-block:: yaml
  803. django:
  804. pip.installed:
  805. - name: django >= 1.6, <= 1.7
  806. - runas: daniel
  807. - require:
  808. - pkg: python-pip
  809. In the above state, the pip command run by ``cmd.run`` will be run by the daniel user.
  810. runas_password
  811. ~~~~~~~~~~~~~~
  812. .. versionadded:: 2017.7.2
  813. The ``runas_password`` global option is used to set the password used by the
  814. runas global option. This is required by ``cmd.run`` on Windows when ``runas``
  815. is specified. It will be set when ``runas_password`` is defined in the state.
  816. .. code-block:: yaml
  817. run_script:
  818. cmd.run:
  819. - name: Powershell -NonInteractive -ExecutionPolicy Bypass -File C:\\Temp\\script.ps1
  820. - runas: frank
  821. - runas_password: supersecret
  822. In the above state, the Powershell script run by ``cmd.run`` will be run by the
  823. frank user with the password ``supersecret``.
  824. check_cmd
  825. ~~~~~~~~~
  826. .. versionadded:: 2014.7.0
  827. Check Command is used for determining that a state did or did not run as
  828. expected.
  829. **NOTE**: Under the hood ``check_cmd`` calls ``cmd.retcode`` with
  830. ``python_shell=True``. This means the commands referenced by unless will be
  831. parsed by a shell, so beware of side-effects as this shell will be run with the
  832. same privileges as the salt-minion.
  833. .. code-block:: yaml
  834. comment-repo:
  835. file.replace:
  836. - name: /etc/yum.repos.d/fedora.repo
  837. - pattern: '^enabled=0'
  838. - repl: enabled=1
  839. - check_cmd:
  840. - "! grep 'enabled=0' /etc/yum.repos.d/fedora.repo"
  841. This will attempt to do a replace on all ``enabled=0`` in the .repo file, and
  842. replace them with ``enabled=1``. The ``check_cmd`` is just a bash command. It
  843. will do a grep for ``enabled=0`` in the file, and if it finds any, it will
  844. return a 0, which will be inverted by the leading ``!``, causing ``check_cmd``
  845. to set the state as failed. If it returns a 1, meaning it didn't find any
  846. ``enabled=0``, it will be inverted by the leading ``!``, returning a 0, and
  847. declaring the function succeeded.
  848. **NOTE**: This requisite ``check_cmd`` functions differently than the ``check_cmd``
  849. of the ``file.managed`` state.
  850. Overriding Checks
  851. ~~~~~~~~~~~~~~~~~
  852. There are two commands used for the above checks.
  853. ``mod_run_check`` is used to check for ``onlyif`` and ``unless``. If the goal is to
  854. override the global check for these to variables, include a ``mod_run_check`` in the
  855. salt/states/ file.
  856. ``mod_run_check_cmd`` is used to check for the check_cmd options. To override
  857. this one, include a ``mod_run_check_cmd`` in the states file for the state.
  858. Fire Event Notifications
  859. ========================
  860. .. versionadded:: 2015.8.0
  861. The `fire_event` option in a state will cause the minion to send an event to
  862. the Salt Master upon completion of that individual state.
  863. The following example will cause the minion to send an event to the Salt Master
  864. with a tag of `salt/state_result/20150505121517276431/dasalt/nano` and the
  865. result of the state will be the data field of the event. Notice that the `name`
  866. of the state gets added to the tag.
  867. .. code-block:: yaml
  868. nano_stuff:
  869. pkg.installed:
  870. - name: nano
  871. - fire_event: True
  872. In the following example instead of setting `fire_event` to `True`,
  873. `fire_event` is set to an arbitrary string, which will cause the event to be
  874. sent with this tag:
  875. `salt/state_result/20150505121725642845/dasalt/custom/tag/nano/finished`
  876. .. code-block:: yaml
  877. nano_stuff:
  878. pkg.installed:
  879. - name: nano
  880. - fire_event: custom/tag/nano/finished
  881. Retrying States
  882. ===============
  883. .. versionadded:: 2017.7.0
  884. The retry option in a state allows it to be executed multiple times until a desired
  885. result is obtained or the maximum number of attempts have been made.
  886. The retry option can be configured by the ``attempts``, ``until``, ``interval``, and
  887. ``splay`` parameters.
  888. The ``attempts`` parameter controls the maximum number of times the state will be
  889. run. If not specified or if an invalid value is specified, ``attempts`` will default
  890. to ``2``.
  891. The ``until`` parameter defines the result that is required to stop retrying the state.
  892. If not specified or if an invalid value is specified, ``until`` will default to ``True``
  893. The ``interval`` parameter defines the amount of time, in seconds, that the system
  894. will wait between attempts. If not specified or if an invalid value is specified,
  895. ``interval`` will default to ``30``.
  896. The ``splay`` parameter allows the ``interval`` to be additionally spread out. If not
  897. specified or if an invalid value is specified, ``splay`` defaults to ``0`` (i.e. no
  898. splaying will occur).
  899. The following example will run the pkg.installed state until it returns ``True`` or it has
  900. been run ``5`` times. Each attempt will be ``60`` seconds apart and the interval will be splayed
  901. up to an additional ``10`` seconds:
  902. .. code-block:: yaml
  903. my_retried_state:
  904. pkg.installed:
  905. - name: nano
  906. - retry:
  907. attempts: 5
  908. until: True
  909. interval: 60
  910. splay: 10
  911. The following example will run the pkg.installed state with all the defaults for ``retry``.
  912. The state will run up to ``2`` times, each attempt being ``30`` seconds apart, or until it
  913. returns ``True``.
  914. .. code-block:: yaml
  915. install_nano:
  916. pkg.installed:
  917. - name: nano
  918. - retry: True
  919. The following example will run the file.exists state every ``30`` seconds up to ``15`` times
  920. or until the file exists (i.e. the state returns ``True``).
  921. .. code-block:: yaml
  922. wait_for_file:
  923. file.exists:
  924. - name: /path/to/file
  925. - retry:
  926. attempts: 15
  927. interval: 30
  928. Return data from a retried state
  929. --------------------------------
  930. When a state is retried, the returned output is as follows:
  931. The ``result`` return value is the ``result`` from the final run. For example, imagine a state set
  932. to ``retry`` up to three times or ``until`` ``True``. If the state returns ``False`` on the first run
  933. and then ``True`` on the second, the ``result`` of the state will be ``True``.
  934. The ``started`` return value is the ``started`` from the first run.
  935. The ``duration`` return value is the total duration of all attempts plus the retry intervals.
  936. The ``comment`` return value will include the result and comment from all previous attempts.
  937. For example:
  938. .. code-block:: yaml
  939. wait_for_file:
  940. file.exists:
  941. - name: /path/to/file
  942. - retry:
  943. attempts: 10
  944. interval: 2
  945. splay: 5
  946. Would return similar to the following. The state result in this case is ``False`` (file.exist was run 10
  947. times with a 2 second interval, but the file specified did not exist on any run).
  948. .. code-block:: none
  949. ID: wait_for_file
  950. Function: file.exists
  951. Result: False
  952. Comment: Attempt 1: Returned a result of "False", with the following comment: "Specified path /path/to/file does not exist"
  953. Attempt 2: Returned a result of "False", with the following comment: "Specified path /path/to/file does not exist"
  954. Attempt 3: Returned a result of "False", with the following comment: "Specified path /path/to/file does not exist"
  955. Attempt 4: Returned a result of "False", with the following comment: "Specified path /path/to/file does not exist"
  956. Attempt 5: Returned a result of "False", with the following comment: "Specified path /path/to/file does not exist"
  957. Attempt 6: Returned a result of "False", with the following comment: "Specified path /path/to/file does not exist"
  958. Attempt 7: Returned a result of "False", with the following comment: "Specified path /path/to/file does not exist"
  959. Attempt 8: Returned a result of "False", with the following comment: "Specified path /path/to/file does not exist"
  960. Attempt 9: Returned a result of "False", with the following comment: "Specified path /path/to/file does not exist"
  961. Specified path /path/to/file does not exist
  962. Started: 09:08:12.903000
  963. Duration: 47000.0 ms
  964. Changes: