Debian Codegraph @

ansible_collections/community/general/docs/docsite/rst/guide_cmdrunner.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_cmdrunner:
7
8
9 Command Runner guide
10 ====================
11
12
13 Introduction
14 ^^^^^^^^^^^^
15
16 The ``ansible_collections.community.general.plugins.module_utils._cmd_runner`` module util provides the
17 ``CmdRunner`` class to help execute external commands. The class is a wrapper around
18 the standard ``AnsibleModule.run_command()`` method, handling command arguments, localization setting,
19 output processing output, check mode, and other features.
20
21 It is even more useful when one command is used in multiple modules, so that you can define all options
22 in a module util file, and each module uses the same runner with different arguments.
23
24 For the sake of clarity, throughout this guide, unless otherwise specified, we use the term *option* when referring to
25 Ansible module options, and the term *argument* when referring to the command line arguments for the external command.
26
27
28 Quickstart
29 """"""""""
30
31 ``CmdRunner`` defines a command and a set of coded instructions on how to format
32 the command-line arguments, in which specific order, for a particular execution.
33 It relies on ``ansible.module_utils.basic.AnsibleModule.run_command()`` to actually execute the command.
34 There are other features, see more details throughout this document.
35
36 To use ``CmdRunner`` you must start by creating an object. The example below is a simplified
37 version of the actual code in :ansplugin:`community.general.ansible_galaxy_install#module`:
38
39 .. code-block:: python
40
41 from ansible_collections.community.general.plugins.module_utils._cmd_runner import CmdRunner, cmd_runner_fmt
42
43 runner = CmdRunner(
44 module,
45 command="ansible-galaxy",
46 arg_formats=dict(
47 type=cmd_runner_fmt.as_func(lambda v: [] if v == 'both' else [v]),
48 galaxy_cmd=cmd_runner_fmt.as_list(),
49 upgrade=cmd_runner_fmt.as_bool("--upgrade"),
50 requirements_file=cmd_runner_fmt.as_opt_val('-r'),
51 dest=cmd_runner_fmt.as_opt_val('-p'),
52 force=cmd_runner_fmt.as_bool("--force"),
53 no_deps=cmd_runner_fmt.as_bool("--no-deps"),
54 version=cmd_runner_fmt.as_fixed("--version"),
55 name=cmd_runner_fmt.as_list(),
56 )
57 )
58
59 This is meant to be done once, then every time you need to execute the command you create a context and pass values as needed:
60
61 .. code-block:: python
62
63 # Run the command with these arguments, when values exist for them
64 with runner("type galaxy_cmd upgrade force no_deps dest requirements_file name", output_process=process) as ctx:
65 ctx.run(galaxy_cmd="install", upgrade=upgrade)
66
67 # version is fixed, requires no value
68 with runner("version") as ctx:
69 dummy, stdout, dummy = ctx.run()
70
71 # passes arg 'data' to AnsibleModule.run_command()
72 with runner("type name", data=stdin_data) as ctx:
73 dummy, stdout, dummy = ctx.run()
74
75 # Another way of expressing it
76 dummy, stdout, dummy = runner("version").run()
77
78 Note that you can pass values for the arguments when calling ``run()``, otherwise ``CmdRunner``
79 uses the module options with the exact same names to provide values for the runner arguments.
80 If no value is passed and no module option is found for the name specified, then an exception is raised, unless
81 the argument is using ``cmd_runner_fmt.as_fixed`` as format function like the ``version`` in the example above.
82 See more about it below.
83
84 In the first example, values of ``type``, ``force``, ``no_deps`` and others
85 are taken straight from the module, whilst ``galaxy_cmd`` and ``upgrade`` are
86 passed explicitly.
87
88 .. note::
89
90 It is not possible to automatically retrieve values of suboptions.
91
92 That generates a resulting command line similar to (example taken from the
93 output of an integration test):
94
95 .. code-block:: python
96
97 [
98 "<venv>/bin/ansible-galaxy",
99 "collection",
100 "install",
101 "--upgrade",
102 "-p",
103 "<collection-install-path>",
104 "netbox.netbox",
105 ]
106
107
108 Argument formats
109 ^^^^^^^^^^^^^^^^
110
111 As seen in the example, ``CmdRunner`` expects a parameter named ``arg_formats``
112 defining how to format each CLI named argument.
113 An "argument format" is nothing but a function to transform the value of a variable
114 into something formatted for the command line.
115
116
117 Argument format function
118 """"""""""""""""""""""""
119
120 An ``arg_format`` function is defined in the form similar to:
121
122 .. code-block:: python
123
124 def func(value):
125 return ["--some-param-name", value]
126
127 The parameter ``value`` can be of any type - although there are convenience
128 mechanisms to help handling sequence and mapping objects.
129
130 The result is expected to be of the type ``Sequence[str]`` type (most commonly
131 ``list[str]`` or ``tuple[str]``), otherwise it is considered to be a ``str``,
132 and it is coerced into ``list[str]``.
133 This resulting sequence of strings is added to the command line when that
134 argument is actually used.
135
136 For example, if ``func`` returns:
137
138 - ``["nee", 2, "shruberries"]``, the command line adds arguments ``"nee" "2" "shruberries"``.
139 - ``2 == 2``, the command line adds argument ``True``.
140 - ``None``, the command line adds argument ``None``.
141 - ``[]``, the command line adds no command line argument for that particular argument.
142
143
144 Convenience format methods
145 """"""""""""""""""""""""""
146
147 In the same module as ``CmdRunner`` there is a class ``cmd_runner_fmt`` which
148 provides a set of convenience methods that return format functions for common cases.
149 In the first block of code in the `Quickstart`_ section you can see the importing of
150 that class:
151
152 .. code-block:: python
153
154 from ansible_collections.community.general.plugins.module_utils._cmd_runner import CmdRunner, cmd_runner_fmt
155
156 The same example shows how to make use of some of them in the instantiation of the ``CmdRunner`` object.
157 A description of each one of the convenience methods available and examples of how to use them is found below.
158 In these descriptions ``value`` refers to the single parameter passed to the formatting function.
159
160 - ``cmd_runner_fmt.as_list()``
161 This method does not receive any parameter, function returns ``value`` as-is.
162
163 - Creation:
164 ``cmd_runner_fmt.as_list()``
165 - Examples:
166 +----------------------+---------------------+
167 | Value | Outcome |
168 +======================+=====================+
169 | ``["foo", "bar"]`` | ``["foo", "bar"]`` |
170 +----------------------+---------------------+
171 | ``"foobar"`` | ``["foobar"]`` |
172 +----------------------+---------------------+
173
174 - ``cmd_runner_fmt.as_bool()``
175 This method receives two different parameters: ``args_true`` and ``args_false``, latter being optional.
176 If the boolean evaluation of ``value`` is ``True``, the format function returns ``args_true``.
177 If the boolean evaluation is ``False``, then the function returns ``args_false`` if it was provided, or ``[]`` otherwise.
178
179 - Creation (one arg):
180 ``cmd_runner_fmt.as_bool("--force")``
181 - Examples:
182 +------------+--------------------+
183 | Value | Outcome |
184 +============+====================+
185 | ``True`` | ``["--force"]`` |
186 +------------+--------------------+
187 | ``False`` | ``[]`` |
188 +------------+--------------------+
189 - Creation (two args, ``None`` treated as ``False``):
190 ``cmd_runner_fmt.as_bool("--relax", "--dont-do-it")``
191 - Examples:
192 +------------+----------------------+
193 | Value | Outcome |
194 +============+======================+
195 | ``True`` | ``["--relax"]`` |
196 +------------+----------------------+
197 | ``False`` | ``["--dont-do-it"]`` |
198 +------------+----------------------+
199 | | ``["--dont-do-it"]`` |
200 +------------+----------------------+
201 - Creation (two args, ``None`` is ignored):
202 ``cmd_runner_fmt.as_bool("--relax", "--dont-do-it", ignore_none=True)``
203 - Examples:
204 +------------+----------------------+
205 | Value | Outcome |
206 +============+======================+
207 | ``True`` | ``["--relax"]`` |
208 +------------+----------------------+
209 | ``False`` | ``["--dont-do-it"]`` |
210 +------------+----------------------+
211 | | ``[]`` |
212 +------------+----------------------+
213
214 - ``cmd_runner_fmt.as_bool_not()``
215 This method receives one parameter, which is returned by the function when the boolean evaluation
216 of ``value`` is ``False``.
217
218 - Creation:
219 ``cmd_runner_fmt.as_bool_not("--no-deps")``
220 - Examples:
221 +-------------+---------------------+
222 | Value | Outcome |
223 +=============+=====================+
224 | ``True`` | ``[]`` |
225 +-------------+---------------------+
226 | ``False`` | ``["--no-deps"]`` |
227 +-------------+---------------------+
228
229 - ``cmd_runner_fmt.as_optval()``
230 This method receives one parameter ``arg``, the function returns the string concatenation
231 of ``arg`` and ``value``.
232
233 - Creation:
234 ``cmd_runner_fmt.as_optval("-i")``
235 - Examples:
236 +---------------+---------------------+
237 | Value | Outcome |
238 +===============+=====================+
239 | ``3`` | ``["-i3"]`` |
240 +---------------+---------------------+
241 | ``foobar`` | ``["-ifoobar"]`` |
242 +---------------+---------------------+
243
244 - ``cmd_runner_fmt.as_opt_val()``
245 This method receives one parameter ``arg``, the function returns ``[arg, value]``.
246
247 - Creation:
248 ``cmd_runner_fmt.as_opt_val("--name")``
249 - Examples:
250 +--------------+--------------------------+
251 | Value | Outcome |
252 +==============+==========================+
253 | ``abc`` | ``["--name", "abc"]`` |
254 +--------------+--------------------------+
255
256 - ``cmd_runner_fmt.as_opt_eq_val()``
257 This method receives one parameter ``arg``, the function returns the string of the form
258 ``{arg}={value}``.
259
260 - Creation:
261 ``cmd_runner_fmt.as_opt_eq_val("--num-cpus")``
262 - Examples:
263 +------------+-------------------------+
264 | Value | Outcome |
265 +============+=========================+
266 | ``10`` | ``["--num-cpus=10"]`` |
267 +------------+-------------------------+
268
269 - ``cmd_runner_fmt.as_fixed()``
270 This method defines one or more fixed arguments that are returned by the generated function
271 regardless whether ``value`` is passed to it or not.
272
273 This method accepts these arguments in one of three forms:
274
275 * one scalar parameter ``arg``, which will be returned as ``[arg]`` by the function, or
276 * one sequence parameter, such as a list, ``arg``, which will be returned by the function as ``arg[0]``, or
277 * multiple parameters ``args``, which will be returned as ``args`` directly by the function.
278
279 See the examples below for each one of those forms. And, stressing that the generated function expects no ``value`` - if one
280 is provided then it is ignored.
281
282 - Creation (one scalar argument):
283 * ``cmd_runner_fmt.as_fixed("--version")``
284 - Examples:
285 +---------+--------------------------------------+
286 | Value | Outcome |
287 +=========+======================================+
288 | | * ``["--version"]`` |
289 +---------+--------------------------------------+
290 | 57 | * ``["--version"]`` |
291 +---------+--------------------------------------+
292
293 - Creation (one sequence argument):
294 * ``cmd_runner_fmt.as_fixed(["--list", "--json"])``
295 - Examples:
296 +---------+--------------------------------------+
297 | Value | Outcome |
298 +=========+======================================+
299 | | * ``["--list", "--json"]`` |
300 +---------+--------------------------------------+
301 | True | * ``["--list", "--json"]`` |
302 +---------+--------------------------------------+
303
304 - Creation (multiple arguments):
305 * ``cmd_runner_fmt.as_fixed("--one", "--two", "--three")``
306 - Examples:
307 +---------+--------------------------------------+
308 | Value | Outcome |
309 +=========+======================================+
310 | | * ``["--one", "--two", "--three"]`` |
311 +---------+--------------------------------------+
312 | False | * ``["--one", "--two", "--three"]`` |
313 +---------+--------------------------------------+
314
315 - Note:
316 This is the only special case in which a value can be missing for the formatting function.
317 The first example here comes from the code in `Quickstart`_.
318 In that case, the module has code to determine the command's version so that it can assert compatibility.
319 There is no *value* to be passed for that CLI argument.
320
321 - ``cmd_runner_fmt.as_map()``
322 This method receives one parameter ``arg`` which must be a dictionary, and an optional parameter ``default``.
323 The function returns the evaluation of ``arg[value]``.
324 If ``value not in arg``, then it returns ``default`` if defined, otherwise ``[]``.
325
326 - Creation:
327 ``cmd_runner_fmt.as_map(dict(a=1, b=2, c=3), default=42)``
328 - Examples:
329 +---------------------+---------------+
330 | Value | Outcome |
331 +=====================+===============+
332 | ``"b"`` | ``["2"]`` |
333 +---------------------+---------------+
334 | ``"yabadabadoo"`` | ``["42"]`` |
335 +---------------------+---------------+
336
337 - Note:
338 If ``default`` is not specified, invalid values return an empty list, meaning they are silently ignored.
339
340 - ``cmd_runner_fmt.as_func()``
341 This method receives one parameter ``arg`` which is itself is a format function and it must abide by the rules described above.
342
343 - Creation:
344 ``cmd_runner_fmt.as_func(lambda v: [] if v == 'stable' else ['--channel', '{0}'.format(v)])``
345 - Note:
346 The outcome for that depends entirely on the function provided by the developer.
347
348
349 Other features for argument formatting
350 """"""""""""""""""""""""""""""""""""""
351
352 Some additional features are available as decorators:
353
354 - ``cmd_runner_fmt.unpack args()``
355 This decorator unpacks the incoming ``value`` as a list of elements.
356
357 For example, in ``ansible_collections.community.general.plugins.module_utils._puppet``, it is used as:
358
359 .. code-block:: python
360
361 @cmd_runner_fmt.unpack_args
362 def execute_func(execute, manifest):
363 if execute:
364 return ["--execute", execute]
365 else:
366 return [manifest]
367
368 runner = CmdRunner(
369 module,
370 command=_prepare_base_cmd(),
371 path_prefix=_PUPPET_PATH_PREFIX,
372 arg_formats=dict(
373 # ...
374 _execute=cmd_runner_fmt.as_func(execute_func),
375 # ...
376 ),
377 )
378
379 Then, in :ansplugin:`community.general.puppet#module` it is put to use with:
380
381 .. code-block:: python
382
383 with runner(args_order) as ctx:
384 rc, stdout, stderr = ctx.run(_execute=[p['execute'], p['manifest']])
385
386 - ``cmd_runner_fmt.unpack_kwargs()``
387 Conversely, this decorator unpacks the incoming ``value`` as a ``dict``-like object.
388
389 - ``cmd_runner_fmt.stack()``
390 This decorator assumes ``value`` is a sequence and concatenates the output
391 of the wrapped function applied to each element of the sequence.
392
393 For example, in :ansplugin:`community.general.django_check#module`, the argument format for ``database``
394 is defined as:
395
396 .. code-block:: python
397
398 arg_formats = dict(
399 # ...
400 database=cmd_runner_fmt.stack(cmd_runner_fmt.as_opt_val)("--database"),
401 # ...
402 )
403
404 When receiving a list ``["abc", "def"]``, the output is:
405
406 .. code-block:: python
407
408 ["--database", "abc", "--database", "def"]
409
410
411 Command Runner
412 ^^^^^^^^^^^^^^
413
414 Settings that can be passed to the ``CmdRunner`` constructor are:
415
416 - ``module: AnsibleModule``
417 Module instance. Mandatory parameter.
418 - ``command: str | list[str]``
419 Command to be executed. It can be a single string, the executable name, or a list
420 of strings containing the executable name as the first element and, optionally, fixed parameters.
421 Those parameters are used in all executions of the runner.
422 The *executable* pointed by this parameter (whether itself when ``str`` or its first element when ``list``) is
423 processed using ``AnsibleModule.get_bin_path()`` *unless* it is an absolute path or contains the character ``/``.
424 - ``arg_formats: dict``
425 Mapping of argument names to formatting functions.
426 - ``default_args_order: str``
427 As the name suggests, a default ordering for the arguments. When
428 this is passed, the context can be created without specifying ``args_order``. Defaults to ``()``.
429 - ``check_rc: bool``
430 When ``True``, if the return code from the command is not zero, the module exits
431 with an error. Defaults to ``False``.
432 - ``path_prefix: list[str]``
433 If the command being executed is installed in a non-standard directory path,
434 additional paths might be provided to search for the executable. Defaults to ``None``.
435 - ``environ_update: dict``
436 Pass additional environment variables to be set during the command execution.
437 Defaults to ``None``.
438 - ``force_lang: str``
439 It is usually important to force the locale to one specific value, so that responses are consistent and, therefore, parseable.
440 Please note that using this option (which is enabled by default) overwrites the environment variables ``LANGUAGE`` and ``LC_ALL``.
441 To disable this mechanism, set this parameter to ``None``.
442 In community.general 9.1.0 a special value ``auto`` was introduced for this parameter, with the effect
443 that ``CmdRunner`` then tries to determine the best parseable locale for the runtime.
444 It should become the default value in the future, but for the time being the default value is ``C``.
445
446 When creating a context, the additional settings that can be passed to the call are:
447
448 - ``args_order: str``
449 Establishes the order in which the arguments are rendered in the command line.
450 This parameter is mandatory unless ``default_args_order`` was provided to the runner instance.
451 - ``output_process: func``
452 Function to transform the output of the executable into different values or formats.
453 See examples in section below.
454 - ``check_mode_skip: bool``
455 Whether to skip the actual execution of the command when the module is in check mode.
456 Defaults to ``False``.
457 - ``check_mode_return: any``
458 If ``check_mode_skip=True``, then return this value instead.
459 - valid named arguments to ``AnsibleModule.run_command()``
460 Other than ``args``, any valid argument to ``run_command()`` can be passed when setting up the run context.
461 For example, ``data`` can be used to send information to the command's standard input.
462 Or ``cwd`` can be used to run the command inside a specific working directory.
463
464 Additionally, any other valid parameters for ``AnsibleModule.run_command()`` may be passed, but unexpected behavior
465 might occur if redefining options already present in the runner or its context creation. Use with caution.
466
467
468 Processing results
469 ^^^^^^^^^^^^^^^^^^
470
471 As mentioned, ``CmdRunner`` uses ``AnsibleModule.run_command()`` to execute the external command,
472 and it passes the return value from that method back to caller. That means that,
473 by default, the result is going to be a tuple ``(rc, stdout, stderr)``.
474
475 If you need to transform or process that output, you can pass a function to the context,
476 as the ``output_process`` parameter. It must be a function like:
477
478 .. code-block:: python
479
480 def process(rc, stdout, stderr):
481 # do some magic
482 return processed_value # whatever that is
483
484 In that case, the return of ``run()`` is the ``processed_value`` returned by the function.
485
486
487 PythonRunner
488 ^^^^^^^^^^^^
489
490 The ``PythonRunner`` class is a specialized version of ``CmdRunner``, geared towards the execution of
491 Python scripts. It features two extra and mutually exclusive parameters ``python`` and ``venv`` in its constructor:
492
493 .. code-block:: python
494
495 from ansible_collections.community.general.plugins.module_utils._python_runner import PythonRunner
496 from ansible_collections.community.general.plugins.module_utils._cmd_runner import cmd_runner_fmt
497
498 runner = PythonRunner(
499 module,
500 command=["-m", "django"],
501 arg_formats=dict(...),
502 python="python",
503 venv="/path/to/some/venv",
504 )
505
506 The default value for ``python`` is the string ``python``, and the for ``venv`` it is ``None``.
507
508 The command line produced by such a command with ``python="python3.12"`` is something like:
509
510 .. code-block:: shell
511
512 /usr/bin/python3.12 -m django <arg1> <arg2> ...
513
514 And the command line for ``venv="/work/venv"`` is like:
515
516 .. code-block:: shell
517
518 /work/venv/bin/python -m django <arg1> <arg2> ...
519
520 You may provide the value of the ``command`` argument as a string (in that case the string is used as a script name)
521 or as a list, in which case the elements of the list must be valid arguments for the Python interpreter, as in the example above.
522 See `Command line and environment <https://docs.python.org/3/using/cmdline.html>`_ for more details.
523
524 If the parameter ``python`` is an absolute path, or contains directory separators, such as ``/``, then it is used
525 as-is, otherwise the runtime ``PATH`` is searched for that command name.
526
527 Other than that, everything else works as in ``CmdRunner``.
528
529 .. versionadded:: 4.8.0