Debian Codegraph @

ansible_collections/community/general/docs/docsite/rst/guide_modulehelper.rst

raw
1 ..
2 Copyright (c) Ansible Project
3 GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
4 SPDX-License-Identifier: GPL-3.0-or-later
5
6 .. _ansible_collections.community.general.docsite.guide_modulehelper:
7
8 Module Helper guide
9 ===================
10
11
12 Introduction
13 ^^^^^^^^^^^^
14
15 Writing a module for Ansible is largely described in existing documentation.
16 However, a good part of that is boilerplate code that needs to be repeated every single time.
17 That is where ``ModuleHelper`` comes to assistance: a lot of that boilerplate code is done.
18
19 .. _ansible_collections.community.general.docsite.guide_modulehelper.quickstart:
20
21 Quickstart
22 """"""""""
23
24 See the `example from Ansible documentation <https://docs.ansible.com/projects/ansible/latest/dev_guide/developing_modules_general.html#creating-a-module>`_
25 written with ``ModuleHelper``.
26 But bear in mind that it does not showcase all of MH's features:
27
28 .. code-block:: python
29
30 from ansible_collections.community.general.plugins.module_utils._module_helper import ModuleHelper
31
32
33 class MyTest(ModuleHelper):
34 module = dict(
35 argument_spec=dict(
36 name=dict(type='str', required=True),
37 new=dict(type='bool', required=False, default=False),
38 ),
39 supports_check_mode=True,
40 )
41
42 def __run__(self):
43 self.vars.original_message = ''
44 self.vars.message = ''
45 if self.check_mode:
46 return
47 self.vars.original_message = self.vars.name
48 self.vars.message = 'goodbye'
49 self.changed = self.vars['new']
50 if self.vars.name == "fail me":
51 self.do_raise("You requested this to fail")
52
53
54 def main():
55 MyTest.execute()
56
57
58 if __name__ == '__main__':
59 main()
60
61
62 Module Helper
63 ^^^^^^^^^^^^^
64
65 Introduction
66 """"""""""""
67
68 ``ModuleHelper`` is a wrapper around the standard ``AnsibleModule``, providing extra features and conveniences.
69 The basic structure of a module using ``ModuleHelper`` is as shown in the
70 :ref:`ansible_collections.community.general.docsite.guide_modulehelper.quickstart`
71 section above, but there are more elements that will take part in it.
72
73 .. code-block:: python
74
75 from ansible_collections.community.general.plugins.module_utils._module_helper import ModuleHelper
76
77
78 class MyTest(ModuleHelper):
79 # behavior for module paramaters ONLY, see below for further information
80 output_params = ()
81 change_params = ()
82 diff_params = ()
83 facts_params = ()
84
85 facts_name = None # used if generating facts, from parameters or otherwise
86
87 module = dict(
88 argument_spec=dict(...),
89 # ...
90 )
91
92 After importing the ``ModuleHelper`` class, you need to declare your own class extending it.
93
94 .. seealso::
95
96 There is a variation called ``StateModuleHelper``, which builds on top of the features provided by MH.
97 See :ref:`ansible_collections.community.general.docsite.guide_modulehelper.statemh` below for more details.
98
99 The easiest way of specifying the module is to create the class variable ``module`` with a dictionary
100 containing the exact arguments that would be passed as parameters to ``AnsibleModule``.
101 If you prefer to create the ``AnsibleModule`` object yourself, just assign it to the ``module`` class variable.
102 MH also accepts a parameter ``module`` in its constructor, if that parameter is used used,
103 then it will override the class variable. The parameter can either be ``dict`` or ``AnsibleModule`` as well.
104
105 Beyond the definition of the module, there are other variables that can be used to control aspects
106 of MH's behavior. These variables should be set at the very beginning of the class, and their semantics are
107 explained through this document.
108
109 The main logic of MH happens in the ``ModuleHelper.run()`` method, which looks like:
110
111 .. code-block:: python
112
113 @module_fails_on_exception
114 def run(self):
115 self.__init_module__()
116 self.__run__()
117 self.__quit_module__()
118 output = self.output
119 if 'failed' not in output:
120 output['failed'] = False
121 self.module.exit_json(changed=self.has_changed(), **output)
122
123 The method ``ModuleHelper.__run__()`` must be implemented by the module and most
124 modules will be able to perform their actions implementing only that MH method.
125 However, in some cases, you might want to execute actions before or after the main tasks, in which cases
126 you should implement ``ModuleHelper.__init_module__()`` and ``ModuleHelper.__quit_module__()`` respectively.
127
128 Note that the output comes from ``self.output``, which is a ``@property`` method.
129 By default, that property will collect all the variables that are marked for output and return them in a dictionary with their values.
130 Moreover, the default ``self.output`` will also handle Ansible ``facts`` and *diff mode*.
131 Also note the changed status comes from ``self.has_changed()``, which is usually calculated from variables that are marked
132 to track changes in their content.
133
134 .. seealso::
135
136 More details in sections
137 :ref:`ansible_collections.community.general.docsite.guide_modulehelper.paramvaroutput` and
138 :ref:`ansible_collections.community.general.docsite.guide_modulehelper.changes` below.
139
140 .. seealso::
141
142 See more about the decorator
143 :ref:`ansible_collections.community.general.docsite.guide_modulehelper.modulefailsdeco` below.
144
145
146 Another way to write the example from the
147 :ref:`ansible_collections.community.general.docsite.guide_modulehelper.quickstart`
148 would be:
149
150 .. code-block:: python
151
152 def __init_module__(self):
153 self.vars.original_message = ''
154 self.vars.message = ''
155
156 def __run__(self):
157 if self.check_mode:
158 return
159 self.vars.original_message = self.vars.name
160 self.vars.message = 'goodbye'
161 self.changed = self.vars['new']
162
163 def __quit_module__(self):
164 if self.vars.name == "fail me":
165 self.do_raise("You requested this to fail")
166
167 Notice that there are no calls to ``module.exit_json()`` nor ``module.fail_json()``: if the module fails, raise an exception.
168 You can use the convenience method ``self.do_raise()`` or raise the exception as usual in Python to do that.
169 If no exception is raised, then the module succeeds.
170
171 .. seealso::
172
173 See more about exceptions in section
174 :ref:`ansible_collections.community.general.docsite.guide_modulehelper.exceptions` below.
175
176 Ansible modules must have a ``main()`` function and the usual test for ``'__main__'``. When using MH that should look like:
177
178 .. code-block:: python
179
180 def main():
181 MyTest.execute()
182
183
184 if __name__ == '__main__':
185 main()
186
187 The class method ``execute()`` is nothing more than a convenience shorcut for:
188
189 .. code-block:: python
190
191 m = MyTest()
192 m.run()
193
194 Optionally, an ``AnsibleModule`` may be passed as parameter to ``execute()``.
195
196 .. _ansible_collections.community.general.docsite.guide_modulehelper.paramvaroutput:
197
198 Parameters, variables, and output
199 """""""""""""""""""""""""""""""""
200
201 All the parameters automatically become variables in the ``self.vars`` attribute, which is of the ``VarDict`` type.
202 By using ``self.vars``, you get a central mechanism to access the parameters but also to expose variables as return values of the module.
203 As described in :ref:`ansible_collections.community.general.docsite.guide_vardict`, variables in ``VarDict`` have metadata associated to them.
204 One of the attributes in that metadata marks the variable for output, and MH makes use of that to generate the module's return values.
205
206 .. note::
207
208 The ``VarDict`` class was introduced in community.general 7.1.0, as part of ``ModuleHelper`` itself.
209 However, it has been factored out to become an utility on its own, described in :ref:`ansible_collections.community.general.docsite.guide_vardict`,
210 and the older implementation was removed in community.general 11.0.0.
211
212 Some code might still refer to the class variables ``use_old_vardict`` and ``mute_vardict_deprecation``, used for the transtition to the new
213 implementation but from community.general 11.0.0 onwards they are no longer used and can be safely removed from the code.
214
215 Contrary to new variables created in ``VarDict``, module parameters are not set for output by default.
216 If you want to include some module parameters in the output, list them in the ``output_params`` class variable.
217
218 .. code-block:: python
219
220 class MyTest(ModuleHelper):
221 output_params = ('state', 'name')
222 ...
223
224 .. important::
225
226 The variable names listed in ``output_params`` **must be module parameters**, as in parameters listed in the module's ``argument_spec``.
227 Names not found in ``argument_spec`` are silently ignored.
228
229 Another neat feature provided by MH by using ``VarDict`` is the automatic tracking of changes when setting the metadata ``change=True``.
230 Again, to enable this feature for module parameters, you must list them in the ``change_params`` class variable.
231
232 .. code-block:: python
233
234 class MyTest(ModuleHelper):
235 # example from community.general.xfconf
236 change_params = ('value', )
237 ...
238
239 .. important::
240
241 The variable names listed in ``change_params`` **must be module parameters**, as in parameters listed in the module's ``argument_spec``.
242 Names not found in ``argument_spec`` are silently ignored.
243
244 .. seealso::
245
246 See more about this in
247 :ref:`ansible_collections.community.general.docsite.guide_modulehelper.changes` below.
248
249 Similarly, if you want to use Ansible's diff mode, you can set the metadata ``diff=True`` and ``diff_params`` for module parameters.
250 With that, MH will automatically generate the diff output for variables that have changed.
251
252 .. code-block:: python
253
254 class MyTest(ModuleHelper):
255 diff_params = ('value', )
256
257 def __run__(self):
258 # example from community.general.gio_mime
259 self.vars.set_meta("handler", initial_value=gio_mime_get(self.runner, self.vars.mime_type), diff=True, change=True)
260
261 .. important::
262
263 The variable names listed in ``diff_params`` **must be module parameters**, as in parameters listed in the module's ``argument_spec``.
264 Names not found in ``argument_spec`` are silently ignored.
265
266 Moreover, if a module is set to return *facts* instead of return values, then again use the metadata ``fact=True`` and ``fact_params`` for module parameters.
267 Additionally, you must specify ``facts_name``, as in:
268
269 .. code-block:: python
270
271 class VolumeFacts(ModuleHelper):
272 facts_name = 'volume_facts'
273
274 def __init_module__(self):
275 self.vars.set("volume", 123, fact=True)
276
277 That generates an Ansible fact like:
278
279 .. code-block:: yaml+jinja
280
281 - name: Obtain volume facts
282 some.collection.volume_facts:
283 # parameters
284
285 - name: Print volume facts
286 debug:
287 msg: Volume fact is {{ ansible_facts.volume_facts.volume }}
288
289 .. important::
290
291 The variable names listed in ``fact_params`` **must be module parameters**, as in parameters listed in the module's ``argument_spec``.
292 Names not found in ``argument_spec`` are silently ignored.
293
294 .. important::
295
296 If ``facts_name`` is not set, the module does not generate any facts.
297
298
299 .. _ansible_collections.community.general.docsite.guide_modulehelper.changes:
300
301 Handling changes
302 """"""""""""""""
303
304 In MH there are many ways to indicate change in the module execution. Here they are:
305
306 Tracking changes in variables
307 -----------------------------
308
309 As explained above, you can enable change tracking in any number of variables in ``self.vars``.
310 By the end of the module execution, if any of those variables has a value different then the first value assigned to them,
311 then that will be picked up by MH and signalled as changed at the module output.
312 See the example below to learn how you can enabled change tracking in variables:
313
314 .. code-block:: python
315
316 # using __init_module__() as example, it works the same in __run__() and __quit_module__()
317 def __init_module__(self):
318 # example from community.general.ansible_galaxy_install
319 self.vars.set("new_roles", {}, change=True)
320
321 # example of "hidden" variable used only to track change in a value from community.general.gconftool2
322 self.vars.set('_value', self.vars.previous_value, output=False, change=True)
323
324 # enable change-tracking without assigning value
325 self.vars.set_meta("new_roles", change=True)
326
327 # if you must forcibly set an initial value to the variable
328 self.vars.set_meta("new_roles", initial_value=[])
329 ...
330
331 If the end value of any variable marked ``change`` is different from its initial value, then MH will return ``changed=True``.
332
333 Indicating changes with ``changed``
334 -----------------------------------
335
336 If you want to indicate change directly in the code, then use the ``self.changed`` property in MH.
337 Beware that this is a ``@property`` method in MH, with both a *getter* and a *setter*.
338 By default, that hidden field is set to ``False``.
339
340 Effective change
341 ----------------
342
343 The effective outcome for the module is determined in the ``self.has_changed()`` method, and it consists of the logical *OR* operation
344 between ``self.changed`` and the change calculated from ``self.vars``.
345
346 .. _ansible_collections.community.general.docsite.guide_modulehelper.exceptions:
347
348 Exceptions
349 """"""""""
350
351 In MH, instead of calling ``module.fail_json()`` you can just raise an exception.
352 The output variables are collected the same way they would be for a successful execution.
353 However, you can set output variables specifically for that exception, if you so choose.
354
355 .. code-block:: python
356
357 from ansible_collections.community.general.plugins.module_utils._module_helper import ModuleHelperException
358
359 def __init_module__(self):
360 if not complex_validation():
361 self.do_raise("Validation failed!")
362
363 # Or passing output variables
364 awesomeness = calculate_awesomeness()
365 if awesomeness > 1000:
366 self.do_raise("Over awesome, I cannot handle it!", update_output={"awesomeness": awesomeness})
367 # which is just a convenience shortcut for
368 raise ModuleHelperException("...", update_output={...})
369
370 All exceptions derived from ``Exception`` are captured and translated into a ``fail_json()`` call.
371 However, if you do want to call ``self.module.fail_json()`` yourself it will work,
372 just keep in mind that there will be no automatic handling of output variables in that case.
373
374 Behind the curtains, all ``do_raise()`` does is to raise a ``ModuleHelperException``.
375 If you want to create specialized error handling for your code, the best way is to extend that clas and raise it when needed.
376
377 .. _ansible_collections.community.general.docsite.guide_modulehelper.statemh:
378
379 StateModuleHelper
380 ^^^^^^^^^^^^^^^^^
381
382 Many modules use a parameter ``state`` that effectively controls the exact action performed by the module, such as
383 ``state=present`` or ``state=absent`` for installing or removing packages.
384 By using ``StateModuleHelper`` you can make your code like the excerpt from the ``gconftool2`` below:
385
386 .. code-block:: python
387
388 from ansible_collections.community.general.plugins.module_utils._module_helper import StateModuleHelper
389
390 class GConftool(StateModuleHelper):
391 ...
392 module = dict(
393 ...
394 )
395
396 def __init_module__(self):
397 self.runner = gconftool2_runner(self.module, check_rc=True)
398 ...
399
400 self.vars.set('previous_value', self._get(), fact=True)
401 self.vars.set('value_type', self.vars.value_type)
402 self.vars.set('_value', self.vars.previous_value, output=False, change=True)
403 self.vars.set_meta('value', initial_value=self.vars.previous_value)
404 self.vars.set('playbook_value', self.vars.value, fact=True)
405
406 ...
407
408 def state_absent(self):
409 with self.runner("state key", output_process=self._make_process(False)) as ctx:
410 ctx.run()
411 self.vars.set('run_info', ctx.run_info, verbosity=4)
412 self.vars.set('new_value', None, fact=True)
413 self.vars._value = None
414
415 def state_present(self):
416 with self.runner("direct config_source value_type state key value", output_process=self._make_process(True)) as ctx:
417 ctx.run()
418 self.vars.set('run_info', ctx.run_info, verbosity=4)
419 self.vars.set('new_value', self._get(), fact=True)
420 self.vars._value = self.vars.new_value
421
422 Note that the method ``__run__()`` is implemented in ``StateModuleHelper``, all you need to implement are the methods ``state_<state_value>``.
423 In the example above, :ansplugin:`community.general.gconftool2#module` only has two states, ``present`` and ``absent``, thus, ``state_present()`` and ``state_absent()``.
424
425 If the controlling parameter is not called ``state``, like in :ansplugin:`community.general.jira#module` module, just let SMH know about it:
426
427 .. code-block:: python
428
429 class JIRA(StateModuleHelper):
430 state_param = 'operation'
431
432 def operation_create(self):
433 ...
434
435 def operation_search(self):
436 ...
437
438 Lastly, if the module is called with ``state=somevalue`` and the method ``state_somevalue``
439 is not implemented, SMH will resort to call a method called ``__state_fallback__()``.
440 By default, this method will raise a ``ValueError`` indicating the method was not found.
441 Naturally, you can override that method to write a default implementation, as in :ansplugin:`community.general.locale_gen#module`:
442
443 .. code-block:: python
444
445 def __state_fallback__(self):
446 if self.vars.state_tracking == self.vars.state:
447 return
448 if self.vars.ubuntu_mode:
449 self.apply_change_ubuntu(self.vars.state, self.vars.name)
450 else:
451 self.apply_change(self.vars.state, self.vars.name)
452
453 That module has only the states ``present`` and ``absent`` and the code for both is the one in the fallback method.
454
455 .. note::
456
457 The name of the fallback method **does not change** if you set a different value of ``state_param``.
458
459
460 Other Conveniences
461 ^^^^^^^^^^^^^^^^^^
462
463 Delegations to AnsibleModule
464 """"""""""""""""""""""""""""
465
466 The MH properties and methods below are delegated as-is to the underlying ``AnsibleModule`` instance in ``self.module``:
467
468 - ``check_mode``
469 - ``get_bin_path()``
470 - ``warn()``
471 - ``deprecate()``
472
473 Additionally, MH will also delegate:
474
475 - ``diff_mode`` to ``self.module._diff``
476 - ``verbosity`` to ``self.module._verbosity``
477
478 Starting in community.general 10.3.0, MH will also delegate the method ``debug`` to ``self.module``.
479 If any existing module already has a ``debug`` attribute defined, a warning message will be generated,
480 requesting it to be renamed. Upon the release of community.general 12.0.0, the delegation will be
481 preemptive and will override any existing method or property in the subclasses.
482
483 Decorators
484 """"""""""
485
486 The following decorators should only be used within ``ModuleHelper`` class.
487
488 @cause_changes
489 --------------
490
491 This decorator will control whether the outcome of the method will cause the module to signal change in its output.
492 If the method completes without raising an exception it is considered to have succeeded, otherwise, it will have failed.
493
494 The decorator has a parameter ``when`` that accepts three different values: ``success``, ``failure``, and ``always``.
495 There are also two legacy parameters, ``on_success`` and ``on_failure``, that will be deprecated, so do not use them.
496 The value of ``changed`` in the module output will be set to ``True``:
497
498 - ``when="success"`` and the method completes without raising an exception.
499 - ``when="failure"`` and the method raises an exception.
500 - ``when="always"``, regardless of the method raising an exception or not.
501
502 .. code-block:: python
503
504 from ansible_collections.community.general.plugins.module_utils._module_helper import cause_changes
505
506 # adapted excerpt from the community.general.jira module
507 class JIRA(StateModuleHelper):
508 @cause_changes(when="success")
509 def operation_create(self):
510 ...
511
512 If ``when`` has a different value or no parameters are specificied, the decorator will have no effect whatsoever.
513
514 .. _ansible_collections.community.general.docsite.guide_modulehelper.modulefailsdeco:
515
516 @module_fails_on_exception
517 --------------------------
518
519 In a method using this decorator, if an exception is raised, the text message of that exception will be captured
520 by the decorator and used to call ``self.module.fail_json()``.
521 In most of the cases there will be no need to use this decorator, because ``ModuleHelper.run()`` already uses it.
522
523 @check_mode_skip
524 ----------------
525
526 If the module is running in check mode, this decorator will prevent the method from executing.
527 The return value in that case is ``None``.
528
529 .. code-block:: python
530
531 from ansible_collections.community.general.plugins.module_utils._module_helper import check_mode_skip
532
533 # adapted excerpt from the community.general.locale_gen module
534 class LocaleGen(StateModuleHelper):
535 @check_mode_skip
536 def __state_fallback__(self):
537 ...
538
539
540 @check_mode_skip_returns
541 ------------------------
542
543 This decorator is similar to the previous one, but the developer can control the return value for the method when running in check mode.
544 It is used with one of two parameters. One is ``callable`` and the return value in check mode will be ``callable(self, *args, **kwargs)``,
545 where ``self`` is the ``ModuleHelper`` instance and the union of ``args`` and ``kwargs`` will contain all the parameters passed to the method.
546
547 The other option is to use the parameter ``value``, in which case the method will return ``value`` when in check mode.
548
549
550 References
551 ^^^^^^^^^^
552
553 - `Ansible Developer Guide <https://docs.ansible.com/projects/ansible/latest/dev_guide/index.html>`_
554 - `Creating a module <https://docs.ansible.com/projects/ansible/latest/dev_guide/developing_modules_general.html#creating-a-module>`_
555 - `Returning ansible facts <https://docs.ansible.com/projects/ansible/latest/reference_appendices/common_return_values.html#ansible-facts>`_
556 - :ref:`ansible_collections.community.general.docsite.guide_vardict`
557
558
559 .. versionadded:: 3.1.0