1.. _developing_modules_documenting:
2.. _module_documenting:
3
4*******************************
5Module format and documentation
6*******************************
7
8If you want to contribute your module to most Ansible collections, you must write your module in Python and follow the standard format described below. (Unless you're writing a Windows module, in which case the :ref:`Windows guidelines <developing_modules_general_windows>` apply.) In addition to following this format, you should review our :ref:`submission checklist <developing_modules_checklist>`, :ref:`programming tips <developing_modules_best_practices>`, and :ref:`strategy for maintaining Python 2 and Python 3 compatibility <developing_python_3>`, as well as information about :ref:`testing <developing_testing>` before you open a pull request.
9
10Every Ansible module written in Python must begin with seven standard sections in a particular order, followed by the code. The sections in order are:
11
12.. contents::
13   :depth: 1
14   :local:
15
16.. note:: Why don't the imports go first?
17
18  Keen Python programmers may notice that contrary to PEP 8's advice we don't put ``imports`` at the top of the file. This is because the ``DOCUMENTATION`` through ``RETURN`` sections are not used by the module code itself; they are essentially extra docstrings for the file. The imports are placed after these special variables for the same reason as PEP 8 puts the imports after the introductory comments and docstrings. This keeps the active parts of the code together and the pieces which are purely informational apart. The decision to exclude E402 is based on readability (which is what PEP 8 is about). Documentation strings in a module are much more similar to module level docstrings, than code, and are never utilized by the module itself. Placing the imports below this documentation and closer to the code, consolidates and groups all related code in a congruent manner to improve readability, debugging and understanding.
19
20.. warning:: **Copy old modules with care!**
21
22  Some older Ansible modules have ``imports`` at the bottom of the file, ``Copyright`` notices with the full GPL prefix, and/or ``DOCUMENTATION`` fields in the wrong order. These are legacy files that need updating - do not copy them into new modules. Over time we are updating and correcting older modules. Please follow the guidelines on this page!
23
24.. _shebang:
25
26Python shebang & UTF-8 coding
27===============================
28
29Begin your Ansible module with ``#!/usr/bin/python`` - this "shebang" allows ``ansible_python_interpreter`` to work. Follow the shebang immediately with ``# -*- coding: utf-8 -*-`` to clarify that the file is UTF-8 encoded.
30
31.. _copyright:
32
33Copyright and license
34=====================
35
36After the shebang and UTF-8 coding, add a `copyright line <https://www.gnu.org/licenses/gpl-howto.en.html>`_ with the original copyright holder and a license declaration. The license declaration should be ONLY one line, not the full GPL prefix.:
37
38.. code-block:: python
39
40    #!/usr/bin/python
41    # -*- coding: utf-8 -*-
42
43    # Copyright: (c) 2018, Terry Jones <terry.jones@example.org>
44    # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
45
46Major additions to the module (for instance, rewrites) may add additional copyright lines. Any legal review will include the source control history, so an exhaustive copyright header is not necessary.
47Please do not edit the existing copyright year. This simplifies project administration and is unlikely to cause any interesting legal issues.
48When adding a second copyright line for a significant feature or rewrite, add the newer line above the older one:
49
50.. code-block:: python
51
52    #!/usr/bin/python
53    # -*- coding: utf-8 -*-
54
55    # Copyright: (c) 2017, [New Contributor(s)]
56    # Copyright: (c) 2015, [Original Contributor(s)]
57    # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
58
59.. _ansible_metadata_block:
60
61ANSIBLE_METADATA block
62======================
63
64Since we moved to collections we have deprecated the METADATA functionality, it is no longer required for modules, but it will not break anything if present.
65
66
67.. _documentation_block:
68
69DOCUMENTATION block
70===================
71
72After the shebang, the UTF-8 coding, the copyright line, and the license section comes the ``DOCUMENTATION`` block. Ansible's online module documentation is generated from the ``DOCUMENTATION`` blocks in each module's source code. The ``DOCUMENTATION`` block must be valid YAML. You may find it easier to start writing your ``DOCUMENTATION`` string in an :ref:`editor with YAML syntax highlighting <other_tools_and_programs>` before you include it in your Python file. You can start by copying our `example documentation string <https://github.com/ansible/ansible/blob/devel/examples/DOCUMENTATION.yml>`_ into your module file and modifying it. If you run into syntax issues in your YAML, you can validate it on the `YAML Lint <http://www.yamllint.com/>`_ website.
73
74Module documentation should briefly and accurately define what each module and option does, and how it works with others in the underlying system. Documentation should be written for broad audience--readable both by experts and non-experts.
75    * Descriptions should always start with a capital letter and end with a full stop. Consistency always helps.
76    * Verify that arguments in doc and module spec dict are identical.
77    * For password / secret arguments ``no_log=True`` should be set.
78    * For arguments that seem to contain sensitive information but **do not** contain secrets, such as "password_length", set ``no_log=False`` to disable the warning message.
79    * If an option is only sometimes required, describe the conditions. For example, "Required when I(state=present)."
80    * If your module allows ``check_mode``, reflect this fact in the documentation.
81
82To create clear, concise, consistent, and useful documentation, follow the :ref:`style guide <style_guide>`.
83
84Each documentation field is described below. Before committing your module documentation, please test it at the command line and as HTML:
85
86* As long as your module file is :ref:`available locally <local_modules>`, you can use ``ansible-doc -t module my_module_name`` to view your module documentation at the command line. Any parsing errors will be obvious - you can view details by adding ``-vvv`` to the command.
87* You should also :ref:`test the HTML output <testing_module_documentation>` of your module documentation.
88
89Documentation fields
90--------------------
91
92All fields in the ``DOCUMENTATION`` block are lower-case. All fields are required unless specified otherwise:
93
94:module:
95
96  * The name of the module.
97  * Must be the same as the filename, without the ``.py`` extension.
98
99:short_description:
100
101  * A short description which is displayed on the :ref:`list_of_collections` page and ``ansible-doc -l``.
102  * The ``short_description`` is displayed by ``ansible-doc -l`` without any category grouping,
103    so it needs enough detail to explain the module's purpose without the context of the directory structure in which it lives.
104  * Unlike ``description:``, ``short_description`` should not have a trailing period/full stop.
105
106:description:
107
108  * A detailed description (generally two or more sentences).
109  * Must be written in full sentences, in other words, with capital letters and periods/full stops.
110  * Shouldn't mention the module name.
111  * Make use of multiple entries rather than using one long paragraph.
112  * Don't quote complete values unless it is required by YAML.
113
114:version_added:
115
116  * The version of Ansible when the module was added.
117  * This is a string, and not a float, for example, ``version_added: '2.1'``.
118  * In collections, this must be the collection version the module was added to, not the Ansible version. For example, ``version_added: 1.0.0``.
119
120:author:
121
122  * Name of the module author in the form ``First Last (@GitHubID)``.
123  * Use a multi-line list if there is more than one author.
124  * Don't use quotes as it should not be required by YAML.
125
126:deprecated:
127
128  * Marks modules that will be removed in future releases. See also :ref:`module_lifecycle`.
129
130:options:
131
132  * Options are often called `parameters` or `arguments`. Because the documentation field is called `options`, we will use that term.
133  * If the module has no options (for example, it's a ``_facts`` module), all you need is one line: ``options: {}``.
134  * If your module has options (in other words, accepts arguments), each option should be documented thoroughly. For each module option, include:
135
136  :option-name:
137
138    * Declarative operation (not CRUD), to focus on the final state, for example `online:`, rather than `is_online:`.
139    * The name of the option should be consistent with the rest of the module, as well as other modules in the same category.
140    * When in doubt, look for other modules to find option names that are used for the same purpose, we like to offer consistency to our users.
141
142  :description:
143
144    * Detailed explanation of what this option does. It should be written in full sentences.
145    * The first entry is a description of the option itself; subsequent entries detail its use, dependencies, or format of possible values.
146    * Should not list the possible values (that's what ``choices:`` is for, though it should explain what the values do if they aren't obvious).
147    * If an option is only sometimes required, describe the conditions. For example, "Required when I(state=present)."
148    * Mutually exclusive options must be documented as the final sentence on each of the options.
149
150  :required:
151
152    * Only needed if ``true``.
153    * If missing, we assume the option is not required.
154
155  :default:
156
157    * If ``required`` is false/missing, ``default`` may be specified (assumed 'null' if missing).
158    * Ensure that the default value in the docs matches the default value in the code.
159    * The default field must not be listed as part of the description, unless it requires additional information or conditions.
160    * If the option is a boolean value, you can use any of the boolean values recognized by Ansible:
161      (such as true/false or yes/no).  Choose the one that reads better in the context of the option.
162
163  :choices:
164
165    * List of option values.
166    * Should be absent if empty.
167
168  :type:
169
170    * Specifies the data type that option accepts, must match the ``argspec``.
171    * If an argument is ``type='bool'``, this field should be set to ``type: bool`` and no ``choices`` should be specified.
172    * If an argument is ``type='list'``, ``elements`` should be specified.
173
174  :elements:
175
176    * Specifies the data type for list elements in case ``type='list'``.
177
178  :aliases:
179    * List of optional name aliases.
180    * Generally not needed.
181
182  :version_added:
183
184    * Only needed if this option was extended after initial Ansible release, in other words, this is greater than the top level `version_added` field.
185    * This is a string, and not a float, for example, ``version_added: '2.3'``.
186    * In collections, this must be the collection version the option was added to, not the Ansible version. For example, ``version_added: 1.0.0``.
187
188  :suboptions:
189
190    * If this option takes a dict or list of dicts, you can define the structure here.
191    * See :ref:`ansible_collections.azure.azcollection.azure_rm_securitygroup_module`, :ref:`ansible_collections.azure.azcollection.azure_rm_azurefirewall_module`, and :ref:`ansible_collections.openstack.cloud.baremetal_node_action_module` for examples.
192
193:requirements:
194
195  * List of requirements (if applicable).
196  * Include minimum versions.
197
198:seealso:
199
200  * A list of references to other modules, documentation or Internet resources
201  * In Ansible 2.10 and later, references to modules must use  the FQCN or ``ansible.builtin`` for modules in ``ansible-core``.
202  * A reference can be one of the following formats:
203
204
205    .. code-block:: yaml+jinja
206
207        seealso:
208
209        # Reference by module name
210        - module: cisco.aci.aci_tenant
211
212        # Reference by module name, including description
213        - module: cisco.aci.aci_tenant
214          description: ACI module to create tenants on a Cisco ACI fabric.
215
216        # Reference by rST documentation anchor
217        - ref: aci_guide
218          description: Detailed information on how to manage your ACI infrastructure using Ansible.
219
220        # Reference by Internet resource
221        - name: APIC Management Information Model reference
222          description: Complete reference of the APIC object model.
223          link: https://developer.cisco.com/docs/apic-mim-ref/
224
225:notes:
226
227  * Details of any important information that doesn't fit in one of the above sections.
228  * For example, whether ``check_mode`` is or is not supported.
229
230
231Linking and other format macros within module documentation
232-----------------------------------------------------------
233
234You can link from your module documentation to other module docs, other resources on docs.ansible.com, and resources elsewhere on the internet with the help of some pre-defined macros. The correct formats for these macros are:
235
236* ``L()`` for links with a heading. For example: ``See L(Ansible Automation Platform,https://www.ansible.com/products/automation-platform).`` As of Ansible 2.10, do not use ``L()`` for relative links between Ansible documentation and collection documentation.
237* ``U()`` for URLs. For example: ``See U(https://www.ansible.com/products/automation-platform) for an overview.``
238
239There are also some macros which do not create links but we use them to display certain types of
240content in a uniform way:
241
242* ``I()`` for option names. For example: ``Required if I(state=present).``  This is italicized in
243  the documentation.
244* ``C()`` for files, option values, and inline code. For example: ``If not set the environment variable C(ACME_PASSWORD) will be used.`` or ``Use C(var | foo.bar.my_filter) to transform C(var) into the required format.``  This displays with a mono-space font in the documentation.
245* ``B()`` currently has no standardized usage.  It is displayed in boldface in the documentation.
246* ``HORIZONTALLINE`` is used sparingly as a separator in long descriptions.  It becomes a horizontal rule (the ``<hr>`` html tag) in the documentation.
247
248.. note::
249
250  For links between modules and documentation within a collection, you can use either of the options above. Use ``U()`` or ``L()`` with full URLs (not relative links).
251
252.. note::
253    - When a collection is not the right granularity, use ``C(..)``:
254
255        - ``The C(win_*) modules (spread across several collections) allow you to manage various aspects of windows hosts.``
256
257.. note::
258
259   Because it stands out better, use ``seealso`` for general references over the use of notes or adding links to the description.
260
261.. _module_docs_fragments:
262
263Documentation fragments
264-----------------------
265
266If you are writing multiple related modules, they may share common documentation, such as authentication details, file mode settings, ``notes:`` or ``seealso:`` entries. Rather than duplicate that information in each module's ``DOCUMENTATION`` block, you can save it once as a doc_fragment plugin and use it in each module's documentation. In Ansible, shared documentation fragments are contained in a ``ModuleDocFragment`` class in `lib/ansible/plugins/doc_fragments/ <https://github.com/ansible/ansible/tree/devel/lib/ansible/plugins/doc_fragments>`_ or the equivalent directory in a collection. To include a documentation fragment, add ``extends_documentation_fragment: FRAGMENT_NAME`` in your module documentation. Use the fully qualified collection name for the FRAGMENT_NAME (for example, ``kubernetes.core.k8s_auth_options``).
267
268Modules should only use items from a doc fragment if the module will implement all of the interface documented there in a manner that behaves the same as the existing modules which import that fragment. The goal is that items imported from the doc fragment will behave identically when used in another module that imports the doc fragment.
269
270By default, only the ``DOCUMENTATION`` property from a doc fragment is inserted into the module documentation. It is possible to define additional properties in the doc fragment in order to import only certain parts of a doc fragment or mix and match as appropriate. If a property is defined in both the doc fragment and the module, the module value overrides the doc fragment.
271
272Here is an example doc fragment named ``example_fragment.py``:
273
274.. code-block:: python
275
276    class ModuleDocFragment(object):
277        # Standard documentation
278        DOCUMENTATION = r'''
279        options:
280          # options here
281        '''
282
283        # Additional section
284        OTHER = r'''
285        options:
286          # other options here
287        '''
288
289
290To insert the contents of ``OTHER`` in a module:
291
292.. code-block:: yaml+jinja
293
294    extends_documentation_fragment: example_fragment.other
295
296Or use both :
297
298.. code-block:: yaml+jinja
299
300    extends_documentation_fragment:
301      - example_fragment
302      - example_fragment.other
303
304.. _note:
305  * Prior to Ansible 2.8, documentation fragments were kept in ``lib/ansible/utils/module_docs_fragments``.
306
307.. versionadded:: 2.8
308
309Since Ansible 2.8, you can have user-supplied doc_fragments by using a ``doc_fragments`` directory adjacent to play or role, just like any other plugin.
310
311For example, all AWS modules should include:
312
313.. code-block:: yaml+jinja
314
315    extends_documentation_fragment:
316    - aws
317    - ec2
318
319:ref:`docfragments_collections` describes how to incorporate documentation fragments in a collection.
320
321.. _examples_block:
322
323EXAMPLES block
324==============
325
326After the shebang, the UTF-8 coding, the copyright line, the license section, and the ``DOCUMENTATION`` block comes the ``EXAMPLES`` block. Here you show users how your module works with real-world examples in multi-line plain-text YAML format. The best examples are ready for the user to copy and paste into a playbook. Review and update your examples with every change to your module.
327
328Per playbook best practices, each example should include a ``name:`` line::
329
330    EXAMPLES = r'''
331    - name: Ensure foo is installed
332      namespace.collection.modulename:
333        name: foo
334        state: present
335    '''
336
337The ``name:`` line should be capitalized and not include a trailing dot.
338
339Use a fully qualified collection name (FQCN) as a part of the module's name like in the example above. For modules in ``ansible-core``, use the ``ansible.builtin.`` identifier, for example ``ansible.builtin.debug``.
340
341If your examples use boolean options, use yes/no values. Since the documentation generates boolean values as yes/no, having the examples use these values as well makes the module documentation more consistent.
342
343If your module returns facts that are often needed, an example of how to use them can be helpful.
344
345.. _return_block:
346
347RETURN block
348============
349
350After the shebang, the UTF-8 coding, the copyright line, the license section, ``DOCUMENTATION`` and ``EXAMPLES`` blocks comes the ``RETURN`` block. This section documents the information the module returns for use by other modules.
351
352If your module doesn't return anything (apart from the standard returns), this section of your module should read: ``RETURN = r''' # '''``
353Otherwise, for each value returned, provide the following fields. All fields are required unless specified otherwise.
354
355:return name:
356  Name of the returned field.
357
358  :description:
359    Detailed description of what this value represents. Capitalized and with trailing dot.
360  :returned:
361    When this value is returned, such as ``always``, ``changed`` or ``success``. This is a string and can contain any human-readable content.
362  :type:
363    Data type.
364  :elements:
365    If ``type='list'``, specifies the data type of the list's elements.
366  :sample:
367    One or more examples.
368  :version_added:
369    Only needed if this return was extended after initial Ansible release, in other words, this is greater than the top level `version_added` field.
370    This is a string, and not a float, for example, ``version_added: '2.3'``.
371  :contains:
372    Optional. To describe nested return values, set ``type: dict``, or ``type: list``/``elements: dict``, or if you really have to, ``type: complex``, and repeat the elements above for each sub-field.
373
374Here are two example ``RETURN`` sections, one with three simple fields and one with a complex nested field::
375
376    RETURN = r'''
377    dest:
378        description: Destination file/path.
379        returned: success
380        type: str
381        sample: /path/to/file.txt
382    src:
383        description: Source file used for the copy on the target machine.
384        returned: changed
385        type: str
386        sample: /home/httpd/.ansible/tmp/ansible-tmp-1423796390.97-147729857856000/source
387    md5sum:
388        description: MD5 checksum of the file after running copy.
389        returned: when supported
390        type: str
391        sample: 2a5aeecc61dc98c4d780b14b330e3282
392    '''
393
394    RETURN = r'''
395    packages:
396        description: Information about package requirements.
397        returned: success
398        type: dict
399        contains:
400            missing:
401                description: Packages that are missing from the system.
402                returned: success
403                type: list
404                elements: str
405                sample:
406                    - libmysqlclient-dev
407                    - libxml2-dev
408            badversion:
409                description: Packages that are installed but at bad versions.
410                returned: success
411                type: list
412                elements: dict
413                sample:
414                    - package: libxml2-dev
415                      version: 2.9.4+dfsg1-2
416                      constraint: ">= 3.0"
417    '''
418
419.. _python_imports:
420
421Python imports
422==============
423
424After the shebang, the UTF-8 coding, the copyright line, the license, and the sections for ``DOCUMENTATION``, ``EXAMPLES``, and ``RETURN``, you can finally add the python imports. All modules must use Python imports in the form:
425
426.. code-block:: python
427
428   from module_utils.basic import AnsibleModule
429
430The use of "wildcard" imports such as ``from module_utils.basic import *`` is no longer allowed.
431
432.. _dev_testing_module_documentation:
433
434Testing module documentation
435============================
436
437To test Ansible documentation locally please :ref:`follow instruction<testing_module_documentation>`.
438