formulas.rst 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353
  1. .. _conventions-formula:
  2. =============
  3. Salt Formulas
  4. =============
  5. Formulas are pre-written Salt States. They are as open-ended as Salt States
  6. themselves and can be used for tasks such as installing a package, configuring,
  7. and starting a service, setting up users or permissions, and many other common
  8. tasks.
  9. All official Salt Formulas are found as separate Git repositories in the
  10. "saltstack-formulas" organization on GitHub:
  11. https://github.com/saltstack-formulas
  12. As a simple example, to install the popular Apache web server (using the normal
  13. defaults for the underlying distro) simply include the
  14. :formula_url:`apache-formula` from a top file:
  15. .. code-block:: yaml
  16. base:
  17. 'web*':
  18. - apache
  19. Installation
  20. ============
  21. Each Salt Formula is an individual Git repository designed as a drop-in
  22. addition to an existing Salt State tree. Formulas can be installed in the
  23. following ways.
  24. Adding a Formula as a GitFS remote
  25. ----------------------------------
  26. One design goal of Salt's GitFS fileserver backend was to facilitate reusable
  27. States. GitFS is a quick and natural way to use Formulas.
  28. 1. :ref:`Install any necessary dependencies and configure GitFS
  29. <tutorial-gitfs>`.
  30. 2. Add one or more Formula repository URLs as remotes in the
  31. :conf_master:`gitfs_remotes` list in the Salt Master configuration file:
  32. .. code-block:: yaml
  33. gitfs_remotes:
  34. - https://github.com/saltstack-formulas/apache-formula
  35. - https://github.com/saltstack-formulas/memcached-formula
  36. **We strongly recommend forking a formula repository** into your own GitHub
  37. account to avoid unexpected changes to your infrastructure.
  38. Many Salt Formulas are highly active repositories so pull new changes with
  39. care. Plus any additions you make to your fork can be easily sent back
  40. upstream with a quick pull request!
  41. 3. Restart the Salt master.
  42. Beginning with the 2018.3.0 release, using formulas with GitFS is now much more
  43. convenient for deployments which use many different fileserver environments
  44. (i.e. saltenvs). Using the :ref:`all_saltenvs <gitfs-global-remotes>`
  45. parameter, files from a single git branch/tag will appear in all environments.
  46. See :ref:`here <gitfs-global-remotes>` for more information on this feature.
  47. Adding a Formula directory manually
  48. -----------------------------------
  49. Formulas are simply directories that can be copied onto the local file system
  50. by using Git to clone the repository or by downloading and expanding a tarball
  51. or zip file of the repository. The directory structure is designed to work with
  52. :conf_master:`file_roots` in the Salt master configuration.
  53. 1. Clone or download the repository into a directory:
  54. .. code-block:: bash
  55. mkdir -p /srv/formulas
  56. cd /srv/formulas
  57. git clone https://github.com/saltstack-formulas/apache-formula.git
  58. # or
  59. mkdir -p /srv/formulas
  60. cd /srv/formulas
  61. wget https://github.com/saltstack-formulas/apache-formula/archive/master.tar.gz
  62. tar xf apache-formula-master.tar.gz
  63. 2. Add the new directory to :conf_master:`file_roots`:
  64. .. code-block:: yaml
  65. file_roots:
  66. base:
  67. - /srv/salt
  68. - /srv/formulas/apache-formula
  69. 3. Restart the Salt Master.
  70. Usage
  71. =====
  72. Each Formula is intended to be immediately usable with sane defaults without
  73. any additional configuration. Many formulas are also configurable by including
  74. data in Pillar; see the :file:`pillar.example` file in each Formula repository
  75. for available options.
  76. Including a Formula in an existing State tree
  77. ---------------------------------------------
  78. Formula may be included in an existing ``sls`` file. This is often useful when
  79. a state you are writing needs to ``require`` or ``extend`` a state defined in
  80. the formula.
  81. Here is an example of a state that uses the :formula_url:`epel-formula` in a
  82. ``require`` declaration which directs Salt to not install the ``python26``
  83. package until after the EPEL repository has also been installed:
  84. .. code-block:: yaml
  85. include:
  86. - epel
  87. python26:
  88. pkg.installed:
  89. - require:
  90. - pkg: epel
  91. Including a Formula from a Top File
  92. -----------------------------------
  93. Some Formula perform completely standalone installations that are not
  94. referenced from other state files. It is usually cleanest to include these
  95. Formula directly from a Top File.
  96. For example the easiest way to set up an OpenStack deployment on a single
  97. machine is to include the :formula_url:`openstack-standalone-formula` directly from
  98. a :file:`top.sls` file:
  99. .. code-block:: yaml
  100. base:
  101. 'myopenstackmaster':
  102. - openstack
  103. Quickly deploying OpenStack across several dedicated machines could also be
  104. done directly from a Top File and may look something like this:
  105. .. code-block:: yaml
  106. base:
  107. 'controller':
  108. - openstack.horizon
  109. - openstack.keystone
  110. 'hyper-*':
  111. - openstack.nova
  112. - openstack.glance
  113. 'storage-*':
  114. - openstack.swift
  115. Configuring Formula using Pillar
  116. --------------------------------
  117. Salt Formulas are designed to work out of the box with no additional
  118. configuration. However, many Formula support additional configuration and
  119. customization through :ref:`Pillar <pillar>`. Examples of available options can
  120. be found in a file named :file:`pillar.example` in the root directory of each
  121. Formula repository.
  122. .. _extending-formulas:
  123. Using Formula with your own states
  124. ----------------------------------
  125. Remember that Formula are regular Salt States and can be used with all Salt's
  126. normal state mechanisms. Formula can be required from other States with
  127. :ref:`requisites-require` declarations, they can be modified using ``extend``,
  128. they can made to watch other states with :ref:`requisites-watch-in`.
  129. The following example uses the stock :formula_url:`apache-formula` alongside a
  130. custom state to create a vhost on a Debian/Ubuntu system and to reload the
  131. Apache service whenever the vhost is changed.
  132. .. code-block:: yaml
  133. # Include the stock, upstream apache formula.
  134. include:
  135. - apache
  136. # Use the watch_in requisite to cause the apache service state to reload
  137. # apache whenever the my-example-com-vhost state changes.
  138. my-example-com-vhost:
  139. file:
  140. - managed
  141. - name: /etc/apache2/sites-available/my-example-com
  142. - watch_in:
  143. - service: apache
  144. Don't be shy to read through the source for each Formula!
  145. Reporting problems & making additions
  146. -------------------------------------
  147. Each Formula is a separate repository on GitHub. If you encounter a bug with a
  148. Formula please file an issue in the respective repository! Send fixes and
  149. additions as a pull request. Add tips and tricks to the repository wiki.
  150. Writing Formulas
  151. ================
  152. Each Formula is a separate repository in the `saltstack-formulas`_ organization
  153. on GitHub.
  154. Get involved creating new Formulas
  155. ----------------------------------
  156. The best way to create new Formula repositories for now is to create a
  157. repository in your own account on GitHub and notify a SaltStack employee when
  158. it is ready. We will add you to the Contributors team on the
  159. `saltstack-formulas`_ organization and help you transfer the repository over.
  160. Ping a SaltStack employee on IRC (``#salt`` on Freenode), join the
  161. ``#formulas`` channel on the `salt-slack`_ (bridged to ``#saltstack-formulas``
  162. on Freenode) or send an email to the `salt-users`_ mailing list. Note that the
  163. IRC logs are available at https://freenode.logbot.info/salt and
  164. https://freenode.logbot.info/saltstack-formulas respectively.
  165. There are a lot of repositories in that organization! Team members can manage
  166. which repositories they are subscribed to on GitHub's watching page:
  167. https://github.com/watching.
  168. Members of the Contributors team are welcome to participate in reviewing pull
  169. requests across the Organization. Some repositories will have regular
  170. contributors and some repositories will not. As you get involved in a
  171. repository be sure to communicate with any other contributors there on pull
  172. requests that are large or have breaking changes.
  173. In general it is best to have another Contributor review and merge any pull
  174. requests that you open. Feel free to `at-mention`_ other regular contributors
  175. to a repository and request a review. However, there are a lot of formula
  176. repositories so if a repository does not yet have regular contributors or if
  177. your pull request has stayed open for more than a couple days feel free to
  178. "selfie-merge" your own pull request.
  179. .. _`at-mention`: https://help.github.com/en/github/writing-on-github/basic-writing-and-formatting-syntax#mentioning-people-and-teams
  180. Style
  181. -----
  182. Maintainability, readability, and reusability are all marks of a good Salt sls
  183. file. This section contains several suggestions and examples.
  184. .. code-block:: jinja
  185. # Deploy the stable master branch unless version overridden by passing
  186. # Pillar at the CLI or via the Reactor.
  187. deploy_myapp:
  188. git.latest:
  189. - name: git@github.com/myco/myapp.git
  190. - version: {{ salt.pillar.get('myapp:version', 'master') }}
  191. Use a descriptive State ID
  192. ``````````````````````````
  193. The ID of a state is used as a unique identifier that may be referenced via
  194. other states in :ref:`requisites <requisites>`. It must be unique across the
  195. whole state tree (:ref:`it is a key in a dictionary <id-declaration>`, after
  196. all).
  197. In addition a state ID should be descriptive and serve as a high-level hint of
  198. what it will do, or manage, or change. For example, ``deploy_webapp``, or
  199. ``apache``, or ``reload_firewall``.
  200. Use ``module.function`` notation
  201. ````````````````````````````````
  202. So-called "short-declaration" notation is preferred for referencing state
  203. modules and state functions. It provides a consistent pattern of
  204. ``module.function`` shared between Salt States, the Reactor, Salt
  205. Mine, the Scheduler, as well as with the CLI.
  206. .. code-block:: yaml
  207. # Do
  208. apache:
  209. pkg.installed:
  210. - name: httpd
  211. # Don't
  212. apache:
  213. pkg:
  214. - installed
  215. - name: httpd
  216. Salt's state compiler will transform "short-decs" into the longer format
  217. :ref:`when compiling the human-friendly highstate structure into the
  218. machine-friendly lowstate structure <state-layers>`.
  219. Specify the ``name`` parameter
  220. ``````````````````````````````
  221. Use a unique and permanent identifier for the state ID and reserve ``name`` for
  222. data with variability.
  223. The :ref:`name declaration <name-declaration>` is a required parameter for all
  224. state functions. The state ID will implicitly be used as ``name`` if it is not
  225. explicitly set in the state.
  226. In many state functions the ``name`` parameter is used for data that varies
  227. such as OS-specific package names, OS-specific file system paths, repository
  228. addresses, etc. Any time the ID of a state changes all references to that ID
  229. must also be changed. Use a permanent ID when writing a state the first time to
  230. future-proof that state and allow for easier refactors down the road.
  231. Comment state files
  232. ```````````````````
  233. YAML allows comments at varying indentation levels. It is a good practice to
  234. comment state files. Use vertical whitespace to visually separate different
  235. concepts or actions.
  236. .. code-block:: yaml
  237. # Start with a high-level description of the current sls file.
  238. # Explain the scope of what it will do or manage.
  239. # Comment individual states as necessary.
  240. update_a_config_file:
  241. # Provide details on why an unusual choice was made. For example:
  242. #
  243. # This template is fetched from a third-party and does not fit our
  244. # company norm of using Jinja. This must be processed using Mako.
  245. file.managed:
  246. - name: /path/to/file.cfg
  247. - source: salt://path/to/file.cfg.template
  248. - template: mako
  249. # Provide a description or explanation that did not fit within the state
  250. # ID. For example:
  251. #
  252. # Update the application's last-deployed timestamp.
  253. # This is a workaround until Bob configures Jenkins to automate RPM
  254. # builds of the app.
  255. cmd.run:
  256. # FIXME: Joe needs this to run on Windows by next quarter. Switch these
  257. # from shell commands to Salt's file.managed and file.replace state
  258. # modules.
  259. - name: |
  260. touch /path/to/file_last_updated
  261. sed -e 's/foo/bar/g' /path/to/file_environment
  262. - onchanges:
  263. - file: a_config_file
  264. Be careful to use Jinja comments for commenting Jinja code and YAML comments
  265. for commenting YAML code.
  266. .. code-block:: jinja
  267. # BAD EXAMPLE
  268. # The Jinja in this YAML comment is still executed!
  269. # {% set apache_is_installed = 'apache' in salt.pkg.list_pkgs() %}
  270. # GOOD EXAMPLE
  271. # The Jinja in this Jinja comment will not be executed.
  272. {# {% set apache_is_installed = 'apache' in salt.pkg.list_pkgs() %} #}
  273. Easy on the Jinja!
  274. ------------------
  275. Jinja templating provides vast flexibility and power when building Salt sls
  276. files. It can also create an unmaintainable tangle of logic and data. Speaking
  277. broadly, Jinja is best used when kept apart from the states (as much as is
  278. possible).
  279. Below are guidelines and examples of how Jinja can be used effectively.
  280. Know the evaluation and execution order
  281. ```````````````````````````````````````
  282. High-level knowledge of how Salt states are compiled and run is useful when
  283. writing states.
  284. The default :conf_minion:`renderer` setting in Salt is Jinja piped to YAML.
  285. Each is a separate step. Each step is not aware of the previous or following
  286. step. Jinja is not YAML aware, YAML is not Jinja aware; they cannot share
  287. variables or interact.
  288. * Whatever the Jinja step produces must be valid YAML.
  289. * Whatever the YAML step produces must be a valid :ref:`highstate data
  290. structure <states-highstate-example>`. (This is also true of the final step
  291. for :ref:`any of the alternate renderers <all-salt.renderers>` in Salt.)
  292. * Highstate can be thought of as a human-friendly data structure; easy to write
  293. and easy to read.
  294. * Salt's state compiler validates the :ref:`highstate <running-highstate>` and
  295. compiles it to low state.
  296. * Low state can be thought of as a machine-friendly data structure. It is a
  297. list of dictionaries that each map directly to a function call.
  298. * Salt's state system finally starts and executes on each "chunk" in the low
  299. state. Remember that requisites are evaluated at runtime.
  300. * The return for each function call is added to the "running" dictionary which
  301. is the final output at the end of the state run.
  302. The full evaluation and execution order::
  303. Jinja -> YAML -> Highstate -> low state -> execution
  304. Avoid changing the underlying system with Jinja
  305. ```````````````````````````````````````````````
  306. Avoid calling commands from Jinja that change the underlying system. Commands
  307. run via Jinja do not respect Salt's dry-run mode (``test=True``)! This is
  308. usually in conflict with the idempotent nature of Salt states unless the
  309. command being run is also idempotent.
  310. Inspect the local system
  311. ````````````````````````
  312. A common use for Jinja in Salt states is to gather information about the
  313. underlying system. The ``grains`` dictionary available in the Jinja context is
  314. a great example of common data points that Salt itself has already gathered.
  315. Less common values are often found by running commands. For example:
  316. .. code-block:: jinja
  317. {% set is_selinux_enabled = salt.cmd.run('sestatus') == '1' %}
  318. This is usually best done with a variable assignment in order to separate the
  319. data from the state that will make use of the data.
  320. Gather external data
  321. ````````````````````
  322. One of the most common uses for Jinja is to pull external data into the state
  323. file. External data can come from anywhere like API calls or database queries,
  324. but it most commonly comes from flat files on the file system or Pillar data
  325. from the Salt Master. For example:
  326. .. code-block:: jinja
  327. {% set some_data = salt.pillar.get('some_data', {'sane default': True}) %}
  328. {# or #}
  329. {% import_yaml 'path/to/file.yaml' as some_data %}
  330. {# or #}
  331. {% import_json 'path/to/file.json' as some_data %}
  332. {# or #}
  333. {% import_text 'path/to/ssh_key.pub' as ssh_pub_key %}
  334. {# or #}
  335. {% from 'path/to/other_file.jinja' import some_data with context %}
  336. This is usually best done with a variable assignment in order to separate the
  337. data from the state that will make use of the data.
  338. Light conditionals and looping
  339. ``````````````````````````````
  340. Jinja is extremely powerful for programmatically generating Salt states. It is
  341. also easy to overuse. As a rule of thumb, if it is hard to read it will be hard
  342. to maintain!
  343. Separate Jinja control-flow statements from the states as much as is possible
  344. to create readable states. Limit Jinja within states to simple variable
  345. lookups.
  346. Below is a simple example of a readable loop:
  347. .. code-block:: jinja
  348. {% for user in salt.pillar.get('list_of_users', []) %}
  349. {# Ensure unique state IDs when looping. #}
  350. {{ user.name }}-{{ loop.index }}:
  351. user.present:
  352. - name: {{ user.name }}
  353. - shell: {{ user.shell }}
  354. {% endfor %}
  355. Avoid putting a Jinja conditionals within Salt states where possible.
  356. Readability suffers and the correct YAML indentation is difficult to see in the
  357. surrounding visual noise. Parametrization (discussed below) and variables are
  358. both useful techniques to avoid this. For example:
  359. .. code-block:: jinja
  360. {# ---- Bad example ---- #}
  361. apache:
  362. pkg.installed:
  363. {% if grains.os_family == 'RedHat' %}
  364. - name: httpd
  365. {% elif grains.os_family == 'Debian' %}
  366. - name: apache2
  367. {% endif %}
  368. {# ---- Better example ---- #}
  369. {% if grains.os_family == 'RedHat' %}
  370. {% set name = 'httpd' %}
  371. {% elif grains.os_family == 'Debian' %}
  372. {% set name = 'apache2' %}
  373. {% endif %}
  374. apache:
  375. pkg.installed:
  376. - name: {{ name }}
  377. {# ---- Good example ---- #}
  378. {% set name = {
  379. 'RedHat': 'httpd',
  380. 'Debian': 'apache2',
  381. }.get(grains.os_family) %}
  382. apache:
  383. pkg.installed:
  384. - name: {{ name }}
  385. Dictionaries are useful to effectively "namespace" a collection of variables.
  386. This is useful with parametrization (discussed below). Dictionaries are also
  387. easily combined and merged. And they can be directly serialized into YAML which
  388. is often easier than trying to create valid YAML through templating. For
  389. example:
  390. .. code-block:: jinja
  391. {# ---- Bad example ---- #}
  392. haproxy_conf:
  393. file.managed:
  394. - name: /etc/haproxy/haproxy.cfg
  395. - template: jinja
  396. {% if 'external_loadbalancer' in grains.roles %}
  397. - source: salt://haproxy/external_haproxy.cfg
  398. {% elif 'internal_loadbalancer' in grains.roles %}
  399. - source: salt://haproxy/internal_haproxy.cfg
  400. {% endif %}
  401. - context:
  402. {% if 'external_loadbalancer' in grains.roles %}
  403. ssl_termination: True
  404. {% elif 'internal_loadbalancer' in grains.roles %}
  405. ssl_termination: False
  406. {% endif %}
  407. {# ---- Better example ---- #}
  408. {% load_yaml as haproxy_defaults %}
  409. common_settings:
  410. bind_port: 80
  411. internal_loadbalancer:
  412. source: salt://haproxy/internal_haproxy.cfg
  413. settings:
  414. bind_port: 8080
  415. ssl_termination: False
  416. external_loadbalancer:
  417. source: salt://haproxy/external_haproxy.cfg
  418. settings:
  419. ssl_termination: True
  420. {% endload %}
  421. {% if 'external_loadbalancer' in grains.roles %}
  422. {% set haproxy = haproxy_defaults['external_loadbalancer'] %}
  423. {% elif 'internal_loadbalancer' in grains.roles %}
  424. {% set haproxy = haproxy_defaults['internal_loadbalancer'] %}
  425. {% endif %}
  426. {% do haproxy.settings.update(haproxy_defaults.common_settings) %}
  427. haproxy_conf:
  428. file.managed:
  429. - name: /etc/haproxy/haproxy.cfg
  430. - template: jinja
  431. - source: {{ haproxy.source }}
  432. - context: {{ haproxy.settings | yaml() }}
  433. There is still room for improvement in the above example. For example,
  434. extracting into an external file or replacing the if-elif conditional with a
  435. function call to filter the correct data more succinctly. However, the state
  436. itself is simple and legible, the data is separate and also simple and legible.
  437. And those suggested improvements can be made at some future date without
  438. altering the state at all!
  439. Avoid heavy logic and programming
  440. `````````````````````````````````
  441. Jinja is not Python. It was made by Python programmers and shares many
  442. semantics and some syntax but it does not allow for abitrary Python function
  443. calls or Python imports. Jinja is a fast and efficient templating language but
  444. the syntax can be verbose and visually noisy.
  445. Once Jinja use within an sls file becomes slightly complicated -- long chains
  446. of if-elif-elif-else statements, nested conditionals, complicated dictionary
  447. merges, wanting to use sets -- instead consider using a different Salt
  448. renderer, such as the Python renderer. As a rule of thumb, if it is hard to
  449. read it will be hard to maintain -- switch to a format that is easier to read.
  450. Using alternate renderers is very simple to do using Salt's "she-bang" syntax
  451. at the top of the file. The Python renderer must simply return the correct
  452. :ref:`highstate data structure <states-highstate-example>`. The following
  453. example is a state tree of two sls files, one simple and one complicated.
  454. ``/srv/salt/top.sls``:
  455. .. code-block:: yaml
  456. base:
  457. '*':
  458. - common_configuration
  459. - roles_configuration
  460. ``/srv/salt/common_configuration.sls``:
  461. .. code-block:: yaml
  462. common_users:
  463. user.present:
  464. - names:
  465. - larry
  466. - curly
  467. - moe
  468. ``/srv/salt/roles_configuration``:
  469. .. code-block:: python
  470. #!py
  471. def run():
  472. list_of_roles = set()
  473. # This example has the minion id in the form 'web-03-dev'.
  474. # Easily access the grains dictionary:
  475. try:
  476. app, instance_number, environment = __grains__["id"].split("-")
  477. instance_number = int(instance_number)
  478. except ValueError:
  479. app, instance_number, environment = ["Unknown", 0, "dev"]
  480. list_of_roles.add(app)
  481. if app == "web" and environment == "dev":
  482. list_of_roles.add("primary")
  483. list_of_roles.add("secondary")
  484. elif app == "web" and environment == "staging":
  485. if instance_number == 0:
  486. list_of_roles.add("primary")
  487. else:
  488. list_of_roles.add("secondary")
  489. # Easily cross-call Salt execution modules:
  490. if __salt__["myutils.query_valid_ec2_instance"]():
  491. list_of_roles.add("is_ec2_instance")
  492. return {
  493. "set_roles_grains": {
  494. "grains.present": [{"name": "roles"}, {"value": list(list_of_roles)},],
  495. },
  496. }
  497. Jinja Macros
  498. ````````````
  499. In Salt sls files Jinja macros are useful for one thing and one thing only:
  500. creating mini templates that can be reused and rendered on demand. Do not fall
  501. into the trap of thinking of macros as functions; Jinja is not Python (see
  502. above).
  503. Macros are useful for creating reusable, parameterized states. For example:
  504. .. code-block:: jinja
  505. {% macro user_state(state_id, user_name, shell='/bin/bash', groups=[]) %}
  506. {{ state_id }}:
  507. user.present:
  508. - name: {{ user_name }}
  509. - shell: {{ shell }}
  510. - groups: {{ groups | json() }}
  511. {% endmacro %}
  512. {% for user_info in salt.pillar.get('my_users', []) %}
  513. {{ user_state('user_number_' ~ loop.index, **user_info) }}
  514. {% endfor %}
  515. Macros are also useful for creating one-off "serializers" that can accept a
  516. data structure and write that out as a domain-specific configuration file. For
  517. example, the following macro could be used to write a php.ini config file:
  518. ``/srv/salt/php.sls``:
  519. .. code-block:: jinja
  520. php_ini:
  521. file.managed:
  522. - name: /etc/php.ini
  523. - source: salt://php.ini.tmpl
  524. - template: jinja
  525. - context:
  526. php_ini_settings: {{ salt.pillar.get('php_ini', {}) | json() }}
  527. ``/srv/pillar/php.sls``:
  528. .. code-block:: yaml
  529. php_ini:
  530. PHP:
  531. engine: 'On'
  532. short_open_tag: 'Off'
  533. error_reporting: 'E_ALL & ~E_DEPRECATED & ~E_STRICT'
  534. ``/srv/salt/php.ini.tmpl``:
  535. .. code-block:: jinja
  536. {% macro php_ini_serializer(data) %}
  537. {% for section_name, name_val_pairs in data.items() %}
  538. [{{ section_name }}]
  539. {% for name, val in name_val_pairs.items() -%}
  540. {{ name }} = "{{ val }}"
  541. {% endfor %}
  542. {% endfor %}
  543. {% endmacro %}
  544. ; File managed by Salt at <{{ source }}>.
  545. ; Your changes will be overwritten.
  546. {{ php_ini_serializer(php_ini_settings) }}
  547. Abstracting static defaults into a lookup table
  548. -----------------------------------------------
  549. Separate data that a state uses from the state itself to increases the
  550. flexibility and reusability of a state.
  551. An obvious and common example of this is platform-specific package names and
  552. file system paths. Another example is sane defaults for an application, or
  553. common settings within a company or organization. Organizing such data as a
  554. dictionary (aka hash map, lookup table, associative array) often provides a
  555. lightweight namespacing and allows for quick and easy lookups. In addition,
  556. using a dictionary allows for easily merging and overriding static values
  557. within a lookup table with dynamic values fetched from Pillar.
  558. A strong convention in Salt Formulas is to place platform-specific data, such
  559. as package names and file system paths, into a file named :file:`map.jinja`
  560. that is placed alongside the state files.
  561. The following is an example from the MySQL Formula.
  562. The :py:func:`grains.filter_by <salt.modules.grains.filter_by>` function
  563. performs a lookup on that table using the ``os_family`` grain (by default).
  564. The result is that the ``mysql`` variable is assigned to a *subset* of
  565. the lookup table for the current platform. This allows states to reference, for
  566. example, the name of a package without worrying about the underlying OS. The
  567. syntax for referencing a value is a normal dictionary lookup in Jinja, such as
  568. ``{{ mysql['service'] }}`` or the shorthand ``{{ mysql.service }}``.
  569. :file:`map.jinja`:
  570. .. code-block:: jinja
  571. {% set mysql = salt['grains.filter_by']({
  572. 'Debian': {
  573. 'server': 'mysql-server',
  574. 'client': 'mysql-client',
  575. 'service': 'mysql',
  576. 'config': '/etc/mysql/my.cnf',
  577. 'python': 'python-mysqldb',
  578. },
  579. 'RedHat': {
  580. 'server': 'mysql-server',
  581. 'client': 'mysql',
  582. 'service': 'mysqld',
  583. 'config': '/etc/my.cnf',
  584. 'python': 'MySQL-python',
  585. },
  586. 'Gentoo': {
  587. 'server': 'dev-db/mysql',
  588. 'client': 'dev-db/mysql',
  589. 'service': 'mysql',
  590. 'config': '/etc/mysql/my.cnf',
  591. 'python': 'dev-python/mysql-python',
  592. },
  593. }, merge=salt['pillar.get']('mysql:lookup')) %}
  594. Values defined in the map file can be fetched for the current platform in any
  595. state file using the following syntax:
  596. .. code-block:: jinja
  597. {% from "mysql/map.jinja" import mysql with context %}
  598. mysql-server:
  599. pkg.installed:
  600. - name: {{ mysql.server }}
  601. service.running:
  602. - name: {{ mysql.service }}
  603. Organizing Pillar data
  604. ``````````````````````
  605. It is considered a best practice to make formulas expect **all**
  606. formula-related parameters to be placed under second-level ``lookup`` key,
  607. within a main namespace designated for holding data for particular
  608. service/software/etc, managed by the formula:
  609. .. code-block:: yaml
  610. mysql:
  611. lookup:
  612. version: 5.7.11
  613. Collecting common values
  614. ````````````````````````
  615. Common values can be collected into a *base* dictionary. This
  616. minimizes repetition of identical values in each of the
  617. ``lookup_dict`` sub-dictionaries. Now only the values that are
  618. different from the base must be specified by the alternates:
  619. :file:`map.jinja`:
  620. .. code-block:: jinja
  621. {% set mysql = salt['grains.filter_by']({
  622. 'default': {
  623. 'server': 'mysql-server',
  624. 'client': 'mysql-client',
  625. 'service': 'mysql',
  626. 'config': '/etc/mysql/my.cnf',
  627. 'python': 'python-mysqldb',
  628. },
  629. 'Debian': {
  630. },
  631. 'RedHat': {
  632. 'client': 'mysql',
  633. 'service': 'mysqld',
  634. 'config': '/etc/my.cnf',
  635. 'python': 'MySQL-python',
  636. },
  637. 'Gentoo': {
  638. 'server': 'dev-db/mysql',
  639. 'client': 'dev-db/mysql',
  640. 'python': 'dev-python/mysql-python',
  641. },
  642. },
  643. merge=salt['pillar.get']('mysql:lookup'), base='default') %}
  644. Overriding values in the lookup table
  645. `````````````````````````````````````
  646. Allow static values within lookup tables to be overridden. This is a simple
  647. pattern which once again increases flexibility and reusability for state files.
  648. The ``merge`` argument in :py:func:`filter_by <salt.modules.grains.filter_by>`
  649. specifies the location of a dictionary in Pillar that can be used to override
  650. values returned from the lookup table. If the value exists in Pillar it will
  651. take precedence.
  652. This is useful when software or configuration files is installed to
  653. non-standard locations or on unsupported platforms. For example, the following
  654. Pillar would replace the ``config`` value from the call above.
  655. .. code-block:: yaml
  656. mysql:
  657. lookup:
  658. config: /usr/local/etc/mysql/my.cnf
  659. .. note:: Protecting Expansion of Content with Special Characters
  660. When templating keep in mind that YAML does have special characters for
  661. quoting, flows, and other special structure and content. When a Jinja
  662. substitution may have special characters that will be incorrectly parsed by
  663. YAML care must be taken. It is a good policy to use the ``yaml_encode`` or
  664. the ``yaml_dquote`` Jinja filters:
  665. .. code-block:: jinja
  666. {%- set foo = 7.7 %}
  667. {%- set bar = none %}
  668. {%- set baz = true %}
  669. {%- set zap = 'The word of the day is "salty".' %}
  670. {%- set zip = '"The quick brown fox . . ."' %}
  671. foo: {{ foo|yaml_encode }}
  672. bar: {{ bar|yaml_encode }}
  673. baz: {{ baz|yaml_encode }}
  674. zap: {{ zap|yaml_encode }}
  675. zip: {{ zip|yaml_dquote }}
  676. The above will be rendered as below:
  677. .. code-block:: yaml
  678. foo: 7.7
  679. bar: null
  680. baz: true
  681. zap: "The word of the day is \"salty\"."
  682. zip: "\"The quick brown fox . . .\""
  683. The :py:func:`filter_by <salt.modules.grains.filter_by>` function performs a
  684. simple dictionary lookup but also allows for fetching data from Pillar and
  685. overriding data stored in the lookup table. That same workflow can be easily
  686. performed without using ``filter_by``; other dictionaries besides data from
  687. Pillar can also be used.
  688. .. code-block:: jinja
  689. {% set lookup_table = {...} %}
  690. {% do lookup_table.update(salt.pillar.get('my:custom:data')) %}
  691. When to use lookup tables
  692. `````````````````````````
  693. The ``map.jinja`` file is only a convention within Salt Formulas. This greater
  694. pattern is useful for a wide variety of data in a wide variety of workflows.
  695. This pattern is not limited to pulling data from a single file or data source.
  696. This pattern is useful in States, Pillar and the Reactor, for example.
  697. Working with a data structure instead of, say, a config file allows the data to
  698. be cobbled together from multiple sources (local files, remote Pillar, database
  699. queries, etc), combined, overridden, and searched.
  700. Below are a few examples of what lookup tables may be useful for and how they
  701. may be used and represented.
  702. Platform-specific information
  703. .............................
  704. An obvious pattern and one used heavily in Salt Formulas is extracting
  705. platform-specific information such as package names and file system paths in
  706. a file named ``map.jinja``. The pattern is explained in detail above.
  707. Sane defaults
  708. .............
  709. Application settings can be a good fit for this pattern. Store default
  710. settings along with the states themselves and keep overrides and sensitive
  711. settings in Pillar. Combine both into a single dictionary and then write the
  712. application config or settings file.
  713. The example below stores most of the Apache Tomcat ``server.xml`` file
  714. alongside the Tomcat states and then allows values to be updated or augmented
  715. via Pillar. (This example uses the BadgerFish format for transforming JSON to
  716. XML.)
  717. ``/srv/salt/tomcat/defaults.yaml``:
  718. .. code-block:: yaml
  719. Server:
  720. '@port': '8005'
  721. '@shutdown': SHUTDOWN
  722. GlobalNamingResources:
  723. Resource:
  724. '@auth': Container
  725. '@description': User database that can be updated and saved
  726. '@factory': org.apache.catalina.users.MemoryUserDatabaseFactory
  727. '@name': UserDatabase
  728. '@pathname': conf/tomcat-users.xml
  729. '@type': org.apache.catalina.UserDatabase
  730. # <...snip...>
  731. ``/srv/pillar/tomcat.sls``:
  732. .. code-block:: yaml
  733. appX:
  734. server_xml_overrides:
  735. Server:
  736. Service:
  737. '@name': Catalina
  738. Connector:
  739. '@port': '8009'
  740. '@protocol': AJP/1.3
  741. '@redirectPort': '8443'
  742. # <...snip...>
  743. ``/srv/salt/tomcat/server_xml.sls``:
  744. .. code-block:: jinja
  745. {% import_yaml 'tomcat/defaults.yaml' as server_xml_defaults %}
  746. {% set server_xml_final_values = salt.pillar.get(
  747. 'appX:server_xml_overrides',
  748. default=server_xml_defaults,
  749. merge=True)
  750. %}
  751. appX_server_xml:
  752. file.serialize:
  753. - name: /etc/tomcat/server.xml
  754. - dataset: {{ server_xml_final_values | json() }}
  755. - formatter: xml_badgerfish
  756. The :py:func:`file.serialize <salt.states.file.serialize>` state can provide a
  757. shorthand for creating some files from data structures. There are also many
  758. examples within Salt Formulas of creating one-off "serializers" (often as Jinja
  759. macros) that reformat a data structure to a specific config file format. For
  760. example, look at the`Nginx vhosts`_ states or the `php.ini`_ file template.
  761. .. _`Nginx vhosts`: https://github.com/saltstack-formulas/nginx-formula/blob/5cad4512/nginx/ng/vhosts_config.sls
  762. .. _`php.ini`: https://github.com/saltstack-formulas/php-formula/blob/82e2cd3a/php/ng/files/php.ini
  763. Environment specific information
  764. ................................
  765. A single state can be reused when it is parameterized as described in the
  766. section below, by separating the data the state will use from the state that
  767. performs the work. This can be the difference between deploying *Application X*
  768. and *Application Y*, or the difference between production and development. For
  769. example:
  770. ``/srv/salt/app/deploy.sls``:
  771. .. code-block:: jinja
  772. {# Load the map file. #}
  773. {% import_yaml 'app/defaults.yaml' as app_defaults %}
  774. {# Extract the relevant subset for the app configured on the current
  775. machine (configured via a grain in this example). #}
  776. {% app = app_defaults.get(salt.grains.get('role')) %}
  777. {# Allow values from Pillar to (optionally) update values from the lookup
  778. table. #}
  779. {% do app_defaults.update(salt.pillar.get('myapp', {})) %}
  780. deploy_application:
  781. git.latest:
  782. - name: {{ app.repo_url }}
  783. - version: {{ app.version }}
  784. - target: {{ app.deploy_dir }}
  785. myco/myapp/deployed:
  786. event.send:
  787. - data:
  788. version: {{ app.version }}
  789. - onchanges:
  790. - git: deploy_application
  791. ``/srv/salt/app/defaults.yaml``:
  792. .. code-block:: yaml
  793. appX:
  794. repo_url: git@github.com/myco/appX.git
  795. target: /var/www/appX
  796. version: master
  797. appY:
  798. repo_url: git@github.com/myco/appY.git
  799. target: /var/www/appY
  800. version: v1.2.3.4
  801. Single-purpose SLS files
  802. ------------------------
  803. Each sls file in a Formula should strive to do a single thing. This increases
  804. the reusability of this file by keeping unrelated tasks from getting coupled
  805. together.
  806. As an example, the base Apache formula should only install the Apache httpd
  807. server and start the httpd service. This is the basic, expected behavior when
  808. installing Apache. It should not perform additional changes such as set the
  809. Apache configuration file or create vhosts.
  810. If a formula is single-purpose as in the example above, other formulas, and
  811. also other states can ``include`` and use that formula with :ref:`requisites`
  812. without also including undesirable or unintended side-effects.
  813. The following is a best-practice example for a reusable Apache formula. (This
  814. skips platform-specific options for brevity. See the full
  815. :formula_url:`apache-formula` for more.)
  816. .. code-block:: text
  817. # apache/init.sls
  818. apache:
  819. pkg.installed:
  820. [...]
  821. service.running:
  822. [...]
  823. # apache/mod_wsgi.sls
  824. include:
  825. - apache
  826. mod_wsgi:
  827. pkg.installed:
  828. [...]
  829. - require:
  830. - pkg: apache
  831. # apache/conf.sls
  832. include:
  833. - apache
  834. apache_conf:
  835. file.managed:
  836. [...]
  837. - watch_in:
  838. - service: apache
  839. To illustrate a bad example, say the above Apache formula installed Apache and
  840. also created a default vhost. The mod_wsgi state would not be able to include
  841. the Apache formula to create that dependency tree without also installing the
  842. unneeded default vhost.
  843. :ref:`Formulas should be reusable <extending-formulas>`. Avoid coupling
  844. unrelated actions together.
  845. .. _conventions-formula-parameterization:
  846. Parameterization
  847. ----------------
  848. *Parameterization is a key feature of Salt Formulas* and also for Salt
  849. States. Parameterization allows a single Formula to be reused across many
  850. operating systems; to be reused across production, development, or staging
  851. environments; and to be reused by many people all with varying goals.
  852. Writing states, specifying ordering and dependencies is the part that takes the
  853. longest to write and to test. Filling those states out with data such as users
  854. or package names or file locations is the easy part. How many users, what those
  855. users are named, or where the files live are all implementation details that
  856. **should be parameterized**. This separation between a state and the data that
  857. populates a state creates a reusable formula.
  858. In the example below the data that populates the state can come from anywhere
  859. -- it can be hard-coded at the top of the state, it can come from an external
  860. file, it can come from Pillar, it can come from an execution function call, or
  861. it can come from a database query. The state itself doesn't change regardless
  862. of where the data comes from. Production data will vary from development data
  863. will vary from data from one company to another, however the state itself stays
  864. the same.
  865. .. code-block:: jinja
  866. {% set user_list = [
  867. {'name': 'larry', 'shell': 'bash'},
  868. {'name': 'curly', 'shell': 'bash'},
  869. {'name': 'moe', 'shell': 'zsh'},
  870. ] %}
  871. {# or #}
  872. {% set user_list = salt['pillar.get']('user_list') %}
  873. {# or #}
  874. {% load_json "default_users.json" as user_list %}
  875. {# or #}
  876. {% set user_list = salt['acme_utils.get_user_list']() %}
  877. {% for user in list_list %}
  878. {{ user.name }}:
  879. user.present:
  880. - name: {{ user.name }}
  881. - shell: {{ user.shell }}
  882. {% endfor %}
  883. Configuration
  884. -------------
  885. Formulas should strive to use the defaults of the underlying platform, followed
  886. by defaults from the upstream project, followed by sane defaults for the
  887. formula itself.
  888. As an example, a formula to install Apache **should not** change the default
  889. Apache configuration file installed by the OS package. However, the Apache
  890. formula **should** include a state to change or override the default
  891. configuration file.
  892. Pillar overrides
  893. ----------------
  894. Pillar lookups must use the safe :py:func:`~salt.modules.pillar.get`
  895. and must provide a default value. Create local variables using the Jinja
  896. ``set`` construct to increase readability and to avoid potentially hundreds or
  897. thousands of function calls across a large state tree.
  898. .. code-block:: jinja
  899. {% from "apache/map.jinja" import apache with context %}
  900. {% set settings = salt['pillar.get']('apache', {}) %}
  901. mod_status:
  902. file.managed:
  903. - name: {{ apache.conf_dir }}
  904. - source: {{ settings.get('mod_status_conf', 'salt://apache/mod_status.conf') }}
  905. - template: {{ settings.get('template_engine', 'jinja') }}
  906. Any default values used in the Formula must also be documented in the
  907. :file:`pillar.example` file in the root of the repository. Comments should be
  908. used liberally to explain the intent of each configuration value. In addition,
  909. users should be able copy-and-paste the contents of this file into their own
  910. Pillar to make any desired changes.
  911. Scripting
  912. ---------
  913. Remember that both State files and Pillar files can easily call out to Salt
  914. :ref:`execution modules <all-salt.modules>` and have access to all the system
  915. grains as well.
  916. .. code-block:: jinja
  917. {% if '/storage' in salt['mount.active']() %}
  918. /usr/local/etc/myfile.conf:
  919. file:
  920. - symlink
  921. - target: /storage/myfile.conf
  922. {% endif %}
  923. Jinja macros to encapsulate logic or conditionals are discouraged in favor of
  924. :ref:`writing custom execution modules <writing-execution-modules>` in Python.
  925. Repository structure
  926. ====================
  927. A basic Formula repository should have the following layout:
  928. .. code-block:: text
  929. foo-formula
  930. |-- foo/
  931. | |-- map.jinja
  932. | |-- init.sls
  933. | `-- bar.sls
  934. |-- CHANGELOG.rst
  935. |-- LICENSE
  936. |-- pillar.example
  937. |-- README.rst
  938. `-- VERSION
  939. .. seealso:: :formula_url:`template-formula`
  940. The :formula_url:`template-formula` repository has a pre-built layout that
  941. serves as the basic structure for a new formula repository. Just copy the
  942. files from there and edit them.
  943. ``README.rst``
  944. --------------
  945. The README should detail each available ``.sls`` file by explaining what it
  946. does, whether it has any dependencies on other formulas, whether it has a
  947. target platform, and any other installation or usage instructions or tips.
  948. A sample skeleton for the ``README.rst`` file:
  949. .. code-block:: restructuredtext
  950. ===
  951. foo
  952. ===
  953. Install and configure the FOO service.
  954. **NOTE**
  955. See the full `Salt Formulas installation and usage instructions
  956. <https://docs.saltstack.com/en/latest/topics/development/conventions/formulas.html>`_.
  957. Available states
  958. ================
  959. .. contents::
  960. :local:
  961. ``foo``
  962. -------
  963. Install the ``foo`` package and enable the service.
  964. ``foo.bar``
  965. -----------
  966. Install the ``bar`` package.
  967. ``CHANGELOG.rst``
  968. -----------------
  969. The ``CHANGELOG.rst`` file should detail the individual versions, their
  970. release date and a set of bullet points for each version highlighting the
  971. overall changes in a given version of the formula.
  972. A sample skeleton for the `CHANGELOG.rst` file:
  973. :file:`CHANGELOG.rst`:
  974. .. code-block:: restructuredtext
  975. foo formula
  976. ===========
  977. 0.0.2 (2013-01-01)
  978. - Re-organized formula file layout
  979. - Fixed filename used for upstart logger template
  980. - Allow for pillar message to have default if none specified
  981. Versioning
  982. ----------
  983. Formula are versioned according to Semantic Versioning, https://semver.org/.
  984. .. note::
  985. Given a version number MAJOR.MINOR.PATCH, increment the:
  986. #. MAJOR version when you make incompatible API changes,
  987. #. MINOR version when you add functionality in a backwards-compatible manner, and
  988. #. PATCH version when you make backwards-compatible bug fixes.
  989. Additional labels for pre-release and build metadata are available as extensions
  990. to the MAJOR.MINOR.PATCH format.
  991. Formula versions are tracked using Git tags as well as the ``VERSION`` file
  992. in the formula repository. The ``VERSION`` file should contain the currently
  993. released version of the particular formula.
  994. Testing Formulas
  995. ================
  996. A smoke-test for invalid Jinja, invalid YAML, or an invalid Salt state
  997. structure can be performed by with the :py:func:`state.show_sls
  998. <salt.modules.state.show_sls>` function:
  999. .. code-block:: bash
  1000. salt '*' state.show_sls apache
  1001. Salt Formulas can then be tested by running each ``.sls`` file via
  1002. :py:func:`state.apply <salt.modules.state.apply_>` and checking the output for
  1003. the success or failure of each state in the Formula. This should be done for
  1004. each supported platform.
  1005. .. ............................................................................
  1006. .. _`saltstack-formulas`: https://github.com/saltstack-formulas