writing.rst 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487
  1. .. _state-modules:
  2. =============
  3. State Modules
  4. =============
  5. State Modules are the components that map to actual enforcement and management
  6. of Salt states.
  7. .. _writing-state-modules:
  8. States are Easy to Write!
  9. =========================
  10. State Modules should be easy to write and straightforward. The information
  11. passed to the SLS data structures will map directly to the states modules.
  12. Mapping the information from the SLS data is simple, this example should
  13. illustrate:
  14. .. code-block:: yaml
  15. /etc/salt/master: # maps to "name", unless a "name" argument is specified below
  16. file.managed: # maps to <filename>.<function> - e.g. "managed" in https://github.com/saltstack/salt/tree/|repo_primary_branch|/salt/states/file.py
  17. - user: root # one of many options passed to the manage function
  18. - group: root
  19. - mode: 644
  20. - source: salt://salt/master
  21. Therefore this SLS data can be directly linked to a module, function, and
  22. arguments passed to that function.
  23. This does issue the burden, that function names, state names and function
  24. arguments should be very human readable inside state modules, since they
  25. directly define the user interface.
  26. .. admonition:: Keyword Arguments
  27. Salt passes a number of keyword arguments to states when rendering them,
  28. including the environment, a unique identifier for the state, and more.
  29. Additionally, keep in mind that the requisites for a state are part of the
  30. keyword arguments. Therefore, if you need to iterate through the keyword
  31. arguments in a state, these must be considered and handled appropriately.
  32. One such example is in the :mod:`pkgrepo.managed
  33. <salt.states.pkgrepo.managed>` state, which needs to be able to handle
  34. arbitrary keyword arguments and pass them to module execution functions.
  35. An example of how these keyword arguments can be handled can be found
  36. here_.
  37. .. _here: https://github.com/saltstack/salt/blob/v0.16.2/salt/states/pkgrepo.py#L163-183
  38. Best Practices
  39. ==============
  40. A well-written state function will follow these steps:
  41. .. note::
  42. This is an extremely simplified example. Feel free to browse the `source
  43. code`_ for Salt's state modules to see other examples.
  44. .. _`source code`: https://github.com/saltstack/salt/tree/|repo_primary_branch|/salt/states
  45. 1. Set up the return dictionary and perform any necessary input validation
  46. (type checking, looking for use of mutually-exclusive arguments, etc.).
  47. .. code-block:: python
  48. ret = {"name": name, "result": False, "changes": {}, "comment": ""}
  49. if foo and bar:
  50. ret["comment"] = "Only one of foo and bar is permitted"
  51. return ret
  52. 2. Check if changes need to be made. This is best done with an
  53. information-gathering function in an accompanying :ref:`execution module
  54. <writing-execution-modules>`. The state should be able to use the return
  55. from this function to tell whether or not the minion is already in the
  56. desired state.
  57. .. code-block:: python
  58. result = __salt__["modname.check"](name)
  59. 3. If step 2 found that the minion is already in the desired state, then exit
  60. immediately with a ``True`` result and without making any changes.
  61. .. code-block:: python
  62. if result:
  63. ret["result"] = True
  64. ret["comment"] = "{0} is already installed".format(name)
  65. return ret
  66. 4. If step 2 found that changes *do* need to be made, then check to see if the
  67. state was being run in test mode (i.e. with ``test=True``). If so, then exit
  68. with a ``None`` result, a relevant comment, and (if possible) a ``changes``
  69. entry describing what changes would be made.
  70. .. code-block:: python
  71. if __opts__["test"]:
  72. ret["result"] = None
  73. ret["comment"] = "{0} would be installed".format(name)
  74. ret["changes"] = result
  75. return ret
  76. 5. Make the desired changes. This should again be done using a function from an
  77. accompanying execution module. If the result of that function is enough to
  78. tell you whether or not an error occurred, then you can exit with a
  79. ``False`` result and a relevant comment to explain what happened.
  80. .. code-block:: python
  81. result = __salt__["modname.install"](name)
  82. 6. Perform the same check from step 2 again to confirm whether or not the
  83. minion is in the desired state. Just as in step 2, this function should be
  84. able to tell you by its return data whether or not changes need to be made.
  85. .. code-block:: python
  86. ret["changes"] = __salt__["modname.check"](name)
  87. As you can see here, we are setting the ``changes`` key in the return
  88. dictionary to the result of the ``modname.check`` function (just as we did
  89. in step 4). The assumption here is that the information-gathering function
  90. will return a dictionary explaining what changes need to be made. This may
  91. or may not fit your use case.
  92. 7. Set the return data and return!
  93. .. code-block:: python
  94. if ret["changes"]:
  95. ret["comment"] = "{0} failed to install".format(name)
  96. else:
  97. ret["result"] = True
  98. ret["comment"] = "{0} was installed".format(name)
  99. return ret
  100. Using Custom State Modules
  101. ==========================
  102. Before the state module can be used, it must be distributed to minions. This
  103. can be done by placing them into ``salt://_states/``. They can then be
  104. distributed manually to minions by running :mod:`saltutil.sync_states
  105. <salt.modules.saltutil.sync_states>` or :mod:`saltutil.sync_all
  106. <salt.modules.saltutil.sync_all>`. Alternatively, when running a
  107. :ref:`highstate <running-highstate>` custom types will automatically be synced.
  108. NOTE: Writing state modules with hyphens in the filename will cause issues
  109. with !pyobjects routines. Best practice to stick to underscores.
  110. Any custom states which have been synced to a minion, that are named the same
  111. as one of Salt's default set of states, will take the place of the default
  112. state with the same name. Note that a state module's name defaults to one based
  113. on its filename (i.e. ``foo.py`` becomes state module ``foo``), but that its
  114. name can be overridden by using a :ref:`__virtual__ function
  115. <virtual-modules>`.
  116. Cross Calling Execution Modules from States
  117. ===========================================
  118. As with Execution Modules, State Modules can also make use of the ``__salt__``
  119. and ``__grains__`` data. See :ref:`cross calling execution modules
  120. <cross-calling-execution-modules>`.
  121. It is important to note that the real work of state management should not be
  122. done in the state module unless it is needed. A good example is the pkg state
  123. module. This module does not do any package management work, it just calls the
  124. pkg execution module. This makes the pkg state module completely generic, which
  125. is why there is only one pkg state module and many backend pkg execution
  126. modules.
  127. On the other hand some modules will require that the logic be placed in the
  128. state module, a good example of this is the file module. But in the vast
  129. majority of cases this is not the best approach, and writing specific
  130. execution modules to do the backend work will be the optimal solution.
  131. .. _cross-calling-state-modules:
  132. Cross Calling State Modules
  133. ===========================
  134. All of the Salt state modules are available to each other and state modules can call
  135. functions available in other state modules.
  136. The variable ``__states__`` is packed into the modules after they are loaded into
  137. the Salt minion.
  138. The ``__states__`` variable is a :ref:`Python dictionary <python:typesmapping>`
  139. containing all of the state modules. Dictionary keys are strings representing
  140. the names of the modules and the values are the functions themselves.
  141. Salt state modules can be cross-called by accessing the value in the
  142. ``__states__`` dict:
  143. .. code-block:: python
  144. ret = __states__["file.managed"](name="/tmp/myfile", source="salt://myfile")
  145. This code will call the `managed` function in the :mod:`file
  146. <salt.states.file>` state module and pass the arguments ``name`` and ``source``
  147. to it.
  148. .. _state-return-data:
  149. Return Data
  150. ===========
  151. A State Module must return a dict containing the following keys/values:
  152. - **name:** The same value passed to the state as "name".
  153. - **changes:** A dict describing the changes made. Each thing changed should
  154. be a key, with its value being another dict with keys called "old" and "new"
  155. containing the old/new values. For example, the pkg state's **changes** dict
  156. has one key for each package changed, with the "old" and "new" keys in its
  157. sub-dict containing the old and new versions of the package. For example,
  158. the final changes dictionary for this scenario would look something like this:
  159. .. code-block:: python
  160. ret["changes"].update({"my_pkg_name": {"old": "", "new": "my_pkg_name-1.0"}})
  161. - **result:** A tristate value. ``True`` if the action was successful,
  162. ``False`` if it was not, or ``None`` if the state was run in test mode,
  163. ``test=True``, and changes would have been made if the state was not run in
  164. test mode.
  165. +--------------------+-----------+------------------------+
  166. | | live mode | test mode |
  167. +====================+===========+========================+
  168. | no changes | ``True`` | ``True`` |
  169. +--------------------+-----------+------------------------+
  170. | successful changes | ``True`` | ``None`` |
  171. +--------------------+-----------+------------------------+
  172. | failed changes | ``False`` | ``False`` or ``None`` |
  173. +--------------------+-----------+------------------------+
  174. .. note::
  175. Test mode does not predict if the changes will be successful or not,
  176. and hence the result for pending changes is usually ``None``.
  177. However, if a state is going to fail and this can be determined
  178. in test mode without applying the change, ``False`` can be returned.
  179. - **comment:** A list of strings or a single string summarizing the result.
  180. Note that support for lists of strings is available as of Salt 2018.3.0.
  181. Lists of strings will be joined with newlines to form the final comment;
  182. this is useful to allow multiple comments from subparts of a state.
  183. Prefer to keep line lengths short (use multiple lines as needed),
  184. and end with punctuation (e.g. a period) to delimit multiple comments.
  185. .. note::
  186. States should not return data which cannot be serialized such as frozensets.
  187. Test State
  188. ==========
  189. All states should check for and support ``test`` being passed in the options.
  190. This will return data about what changes would occur if the state were actually
  191. run. An example of such a check could look like this:
  192. .. code-block:: python
  193. # Return comment of changes if test.
  194. if __opts__["test"]:
  195. ret["result"] = None
  196. ret["comment"] = "State Foo will execute with param {0}".format(bar)
  197. return ret
  198. Make sure to test and return before performing any real actions on the minion.
  199. .. note::
  200. Be sure to refer to the ``result`` table listed above and displaying any
  201. possible changes when writing support for ``test``. Looking for changes in
  202. a state is essential to ``test=true`` functionality. If a state is predicted
  203. to have no changes when ``test=true`` (or ``test: true`` in a config file)
  204. is used, then the result of the final state **should not** be ``None``.
  205. Watcher Function
  206. ================
  207. If the state being written should support the watch requisite then a watcher
  208. function needs to be declared. The watcher function is called whenever the
  209. watch requisite is invoked and should be generic to the behavior of the state
  210. itself.
  211. The watcher function should accept all of the options that the normal state
  212. functions accept (as they will be passed into the watcher function).
  213. A watcher function typically is used to execute state specific reactive
  214. behavior, for instance, the watcher for the service module restarts the
  215. named service and makes it useful for the watcher to make the service
  216. react to changes in the environment.
  217. The watcher function also needs to return the same data that a normal state
  218. function returns.
  219. Mod_init Interface
  220. ==================
  221. Some states need to execute something only once to ensure that an environment
  222. has been set up, or certain conditions global to the state behavior can be
  223. predefined. This is the realm of the mod_init interface.
  224. A state module can have a function called **mod_init** which executes when the
  225. first state of this type is called. This interface was created primarily to
  226. improve the pkg state. When packages are installed the package metadata needs
  227. to be refreshed, but refreshing the package metadata every time a package is
  228. installed is wasteful. The mod_init function for the pkg state sets a flag down
  229. so that the first, and only the first, package installation attempt will refresh
  230. the package database (the package database can of course be manually called to
  231. refresh via the ``refresh`` option in the pkg state).
  232. The mod_init function must accept the **Low State Data** for the given
  233. executing state as an argument. The low state data is a dict and can be seen by
  234. executing the state.show_lowstate function. Then the mod_init function must
  235. return a bool. If the return value is True, then the mod_init function will not
  236. be executed again, meaning that the needed behavior has been set up. Otherwise,
  237. if the mod_init function returns False, then the function will be called the
  238. next time.
  239. A good example of the mod_init function is found in the pkg state module:
  240. .. code-block:: python
  241. def mod_init(low):
  242. """
  243. Refresh the package database here so that it only needs to happen once
  244. """
  245. if low["fun"] == "installed" or low["fun"] == "latest":
  246. rtag = __gen_rtag()
  247. if not os.path.exists(rtag):
  248. open(rtag, "w+").write("")
  249. return True
  250. else:
  251. return False
  252. The mod_init function in the pkg state accepts the low state data as ``low``
  253. and then checks to see if the function being called is going to install
  254. packages, if the function is not going to install packages then there is no
  255. need to refresh the package database. Therefore if the package database is
  256. prepared to refresh, then return True and the mod_init will not be called
  257. the next time a pkg state is evaluated, otherwise return False and the mod_init
  258. will be called next time a pkg state is evaluated.
  259. Log Output
  260. ==========
  261. You can call the logger from custom modules to write messages to the minion
  262. logs. The following code snippet demonstrates writing log messages:
  263. .. code-block:: python
  264. import logging
  265. log = logging.getLogger(__name__)
  266. log.info("Here is Some Information")
  267. log.warning("You Should Not Do That")
  268. log.error("It Is Busted")
  269. Strings and Unicode
  270. ===================
  271. A state module author should always assume that strings fed to the module
  272. have already decoded from strings into Unicode. In Python 2, these will
  273. be of type 'Unicode' and in Python 3 they will be of type ``str``. Calling
  274. from a state to other Salt sub-systems, such as execution modules should
  275. pass Unicode (or bytes if passing binary data). In the rare event that a state needs to write directly
  276. to disk, Unicode should be encoded to a string immediately before writing
  277. to disk. An author may use ``__salt_system_encoding__`` to learn what the
  278. encoding type of the system is. For example,
  279. `'my_string'.encode(__salt_system_encoding__')`.
  280. Full State Module Example
  281. =========================
  282. The following is a simplistic example of a full state module and function.
  283. Remember to call out to execution modules to perform all the real work. The
  284. state module should only perform "before" and "after" checks.
  285. 1. Make a custom state module by putting the code into a file at the following
  286. path: **/srv/salt/_states/my_custom_state.py**.
  287. 2. Distribute the custom state module to the minions:
  288. .. code-block:: bash
  289. salt '*' saltutil.sync_states
  290. 3. Write a new state to use the custom state by making a new state file, for
  291. instance **/srv/salt/my_custom_state.sls**.
  292. 4. Add the following SLS configuration to the file created in Step 3:
  293. .. code-block:: yaml
  294. human_friendly_state_id: # An arbitrary state ID declaration.
  295. my_custom_state: # The custom state module name.
  296. - enforce_custom_thing # The function in the custom state module.
  297. - name: a_value # Maps to the ``name`` parameter in the custom function.
  298. - foo: Foo # Specify the required ``foo`` parameter.
  299. - bar: False # Override the default value for the ``bar`` parameter.
  300. Example state module
  301. --------------------
  302. .. code-block:: python
  303. import salt.exceptions
  304. def enforce_custom_thing(name, foo, bar=True):
  305. """
  306. Enforce the state of a custom thing
  307. This state module does a custom thing. It calls out to the execution module
  308. ``my_custom_module`` in order to check the current system and perform any
  309. needed changes.
  310. name
  311. The thing to do something to
  312. foo
  313. A required argument
  314. bar : True
  315. An argument with a default value
  316. """
  317. ret = {
  318. "name": name,
  319. "changes": {},
  320. "result": False,
  321. "comment": "",
  322. }
  323. # Start with basic error-checking. Do all the passed parameters make sense
  324. # and agree with each-other?
  325. if bar == True and foo.startswith("Foo"):
  326. raise salt.exceptions.SaltInvocationError(
  327. 'Argument "foo" cannot start with "Foo" if argument "bar" is True.'
  328. )
  329. # Check the current state of the system. Does anything need to change?
  330. current_state = __salt__["my_custom_module.current_state"](name)
  331. if current_state == foo:
  332. ret["result"] = True
  333. ret["comment"] = "System already in the correct state"
  334. return ret
  335. # The state of the system does need to be changed. Check if we're running
  336. # in ``test=true`` mode.
  337. if __opts__["test"] == True:
  338. ret["comment"] = 'The state of "{0}" will be changed.'.format(name)
  339. ret["changes"] = {
  340. "old": current_state,
  341. "new": "Description, diff, whatever of the new state",
  342. }
  343. # Return ``None`` when running with ``test=true``.
  344. ret["result"] = None
  345. return ret
  346. # Finally, make the actual change and return the result.
  347. new_state = __salt__["my_custom_module.change_state"](name, foo)
  348. ret["comment"] = 'The state of "{0}" was changed!'.format(name)
  349. ret["changes"] = {
  350. "old": current_state,
  351. "new": new_state,
  352. }
  353. ret["result"] = True
  354. return ret