Debian Codegraph @

lib/ansible/cli/arguments/option_helpers.py

raw
1 # Copyright: (c) 2018, Ansible Project
2 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
3
4 from __future__ import annotations
5
6 import copy
7 import dataclasses
8 import inspect
9 import operator
10 import argparse
11 import os
12 import os.path
13 import sys
14 import time
15 import typing as t
16
17 import yaml
18
19 import ansible
20 from ansible import constants as C
21 from ansible._internal import _templating
22 from ansible.module_utils.common.text.converters import to_native
23 from ansible.module_utils.common.yaml import HAS_LIBYAML, yaml_load
24 from ansible.release import __version__
25 from ansible.utils.path import unfrackpath
26
27 from ansible._internal._datatag._tags import TrustedAsTemplate, Origin
28
29
30 #
31 # Special purpose OptionParsers
32 #
33 class SortingHelpFormatter(argparse.HelpFormatter):
34 def add_arguments(self, actions):
35 actions = sorted(actions, key=operator.attrgetter('option_strings'))
36 super(SortingHelpFormatter, self).add_arguments(actions)
37
38
39 @dataclasses.dataclass(frozen=True, kw_only=True)
40 class DeprecatedArgument:
41 version: str
42 """The Ansible version that will remove the deprecated argument."""
43
44 option: str | None = None
45 """The specific option string that is deprecated; None applies to all options for this argument."""
46
47 alternatives: str | None = None
48 """The options to use instead."""
49
50 def is_deprecated(self, option: str) -> bool:
51 """Return True if the given option is deprecated, otherwise False."""
52 return self.option is None or option == self.option
53
54 def check(self, option: str) -> None:
55 """Display a deprecation warning if the given option is deprecated."""
56 if not self.is_deprecated(option):
57 return
58
59 from ansible.utils.display import Display
60
61 Display().deprecated( # pylint: disable=ansible-invalid-deprecated-version
62 msg=f'The {option!r} argument is deprecated.',
63 version=self.version,
64 help_text=f'Use {self.alternatives} instead.' if self.alternatives else None
65 )
66
67
68 class ArgumentParser(argparse.ArgumentParser):
69 def __init__(self, *args, **kwargs) -> None:
70 self.__actions: dict[str | None, type[argparse.Action]] = {}
71
72 super().__init__(*args, **kwargs)
73
74 def register(self, registry_name, value, object):
75 """Track registration of actions so that they can be resolved later by name, without depending on the internals of ArgumentParser."""
76 if registry_name == 'action':
77 self.__actions[value] = object
78
79 super().register(registry_name, value, object)
80
81 def _patch_argument(self, args: tuple[str, ...], kwargs: dict[str, t.Any]) -> None:
82 """
83 Patch `kwargs` for an `add_argument` call using the given `args` and `kwargs`.
84 This is used to apply tags to entire categories of CLI arguments.
85 """
86 name = args[0]
87 action = kwargs.get('action')
88 resolved_action = self.__actions.get(action, action) # get the action by name, or use as-is (assume it's a subclass of argparse.Action)
89 action_signature = inspect.signature(resolved_action.__init__)
90
91 if action_signature.parameters.get('type'):
92 arg_type = kwargs.get('type', str)
93
94 if not callable(arg_type):
95 raise ValueError(f'Argument {name!r} requires a callable for the {"type"!r} parameter, not {arg_type!r}.')
96
97 wrapped_arg_type = _tagged_type_factory(name, arg_type)
98
99 kwargs.update(type=wrapped_arg_type)
100
101 def _patch_parser(self, parser):
102 """Patch and return the given parser to intercept the `add_argument` method for further patching."""
103 parser_add_argument = parser.add_argument
104
105 def add_argument(*ag_args, **ag_kwargs):
106 self._patch_argument(ag_args, ag_kwargs)
107
108 parser_add_argument(*ag_args, **ag_kwargs)
109
110 parser.add_argument = add_argument
111
112 return parser
113
114 def add_subparsers(self, *args, **kwargs):
115 sub = super().add_subparsers(*args, **kwargs)
116 sub_add_parser = sub.add_parser
117
118 def add_parser(*sub_args, **sub_kwargs):
119 return self._patch_parser(sub_add_parser(*sub_args, **sub_kwargs))
120
121 sub.add_parser = add_parser
122
123 return sub
124
125 def add_argument_group(self, *args, **kwargs):
126 return self._patch_parser(super().add_argument_group(*args, **kwargs))
127
128 def add_mutually_exclusive_group(self, *args, **kwargs):
129 return self._patch_parser(super().add_mutually_exclusive_group(*args, **kwargs))
130
131 def add_argument(self, *args, **kwargs) -> argparse.Action:
132 action = kwargs.get('action')
133 help = kwargs.get('help')
134 if help and action in {'append', 'append_const', 'count', 'extend', PrependListAction}:
135 help = f'{help.rstrip(".")}. This argument may be specified multiple times.'
136 kwargs['help'] = help
137
138 self._patch_argument(args, kwargs)
139
140 deprecated: DeprecatedArgument | None
141
142 if deprecated := kwargs.pop('deprecated', None):
143 action_type = self.__actions.get(action, action)
144
145 class DeprecatedAction(action_type): # type: ignore[misc, valid-type]
146 """A wrapper around an action which handles deprecation warnings."""
147
148 def __call__(self, parser, namespace, values, option_string=None) -> t.Any:
149 deprecated.check(option_string)
150
151 return super().__call__(parser, namespace, values, option_string)
152
153 kwargs['action'] = DeprecatedAction
154
155 return super().add_argument(*args, **kwargs)
156
157
158 class AnsibleVersion(argparse.Action):
159 def __call__(self, parser, namespace, values, option_string=None):
160 ansible_version = to_native(version(getattr(parser, 'prog')))
161 print(ansible_version)
162 parser.exit()
163
164
165 class UnrecognizedArgument(argparse.Action):
166 def __init__(self, option_strings, dest, const=True, default=None, required=False, help=None, metavar=None, nargs=0):
167 super(UnrecognizedArgument, self).__init__(option_strings=option_strings, dest=dest, nargs=nargs, const=const,
168 default=default, required=required, help=help)
169
170 def __call__(self, parser, namespace, values, option_string=None):
171 parser.error('unrecognized arguments: %s' % option_string)
172
173
174 class PrependListAction(argparse.Action):
175 """A near clone of ``argparse._AppendAction``, but designed to prepend list values
176 instead of appending.
177 """
178 def __init__(self, option_strings, dest, nargs=None, const=None, default=None, type=None,
179 choices=None, required=False, help=None, metavar=None):
180 if nargs == 0:
181 raise ValueError('nargs for append actions must be > 0; if arg '
182 'strings are not supplying the value to append, '
183 'the append const action may be more appropriate')
184 if const is not None and nargs != argparse.OPTIONAL:
185 raise ValueError('nargs must be %r to supply const' % argparse.OPTIONAL)
186 super(PrependListAction, self).__init__(
187 option_strings=option_strings,
188 dest=dest,
189 nargs=nargs,
190 const=const,
191 default=default,
192 type=type,
193 choices=choices,
194 required=required,
195 help=help,
196 metavar=metavar
197 )
198
199 def __call__(self, parser, namespace, values, option_string=None):
200 items = copy.copy(ensure_value(namespace, self.dest, []))
201 items[0:0] = values
202 setattr(namespace, self.dest, items)
203
204
205 def ensure_value(namespace, name, value):
206 if getattr(namespace, name, None) is None:
207 setattr(namespace, name, value)
208 return getattr(namespace, name)
209
210
211 #
212 # Callbacks to validate and normalize Options
213 #
214 def unfrack_path(pathsep=False, follow=True):
215 """Turn an Option's data into a single path in Ansible locations"""
216 def inner(value):
217 if pathsep:
218 return [unfrackpath(x, follow=follow) for x in value.split(os.pathsep) if x]
219
220 if value == '-':
221 return value
222
223 return unfrackpath(value, follow=follow)
224 return inner
225
226
227 def maybe_unfrack_path(beacon):
228
229 def inner(value):
230 if value.startswith(beacon):
231 return beacon + unfrackpath(value[1:])
232 return value
233 return inner
234
235
236 def _git_repo_info(repo_path):
237 """ returns a string containing git branch, commit id and commit date """
238 result = None
239 if os.path.exists(repo_path):
240 # Check if the .git is a file. If it is a file, it means that we are in a submodule structure.
241 if os.path.isfile(repo_path):
242 try:
243 with open(repo_path) as f:
244 gitdir = yaml_load(f).get('gitdir')
245 # There is a possibility the .git file to have an absolute path.
246 if os.path.isabs(gitdir):
247 repo_path = gitdir
248 else:
249 repo_path = os.path.join(repo_path[:-4], gitdir)
250 except (OSError, AttributeError):
251 return ''
252 with open(os.path.join(repo_path, "HEAD")) as f:
253 line = f.readline().rstrip("\n")
254 if line.startswith("ref:"):
255 branch_path = os.path.join(repo_path, line[5:])
256 else:
257 branch_path = None
258 if branch_path and os.path.exists(branch_path):
259 branch = '/'.join(line.split('/')[2:])
260 with open(branch_path) as f:
261 commit = f.readline()[:10]
262 else:
263 # detached HEAD
264 commit = line[:10]
265 branch = 'detached HEAD'
266 branch_path = os.path.join(repo_path, "HEAD")
267
268 date = time.localtime(os.stat(branch_path).st_mtime)
269 if time.daylight == 0:
270 offset = time.timezone
271 else:
272 offset = time.altzone
273 result = "({0} {1}) last updated {2} (GMT {3:+04d})".format(branch, commit, time.strftime("%Y/%m/%d %H:%M:%S", date), int(offset / -36))
274 else:
275 result = ''
276 return result
277
278
279 def _gitinfo():
280 basedir = os.path.normpath(os.path.join(os.path.dirname(__file__), '..', '..', '..', '..'))
281 repo_path = os.path.join(basedir, '.git')
282 return _git_repo_info(repo_path)
283
284
285 def version(prog=None):
286 """ return ansible version """
287 if prog:
288 result = ["{0} [core {1}]".format(prog, __version__)]
289 else:
290 result = [__version__]
291
292 gitinfo = _gitinfo()
293 if gitinfo:
294 result[0] = "{0} {1}".format(result[0], gitinfo)
295 result.append(" config file = %s" % C.CONFIG_FILE)
296 if C.DEFAULT_MODULE_PATH is None:
297 cpath = "Default w/o overrides"
298 else:
299 cpath = C.DEFAULT_MODULE_PATH
300
301 if HAS_LIBYAML:
302 libyaml_fragment = "with libyaml"
303
304 # noinspection PyBroadException
305 try:
306 from yaml._yaml import get_version_string
307
308 libyaml_fragment += f" v{get_version_string()}"
309 except Exception: # pylint: disable=broad-except
310 libyaml_fragment += ", version unknown"
311 else:
312 libyaml_fragment = "without libyaml"
313
314 result.append(" configured module search path = %s" % cpath)
315 result.append(" ansible python module location = %s" % ':'.join(ansible.__path__))
316 result.append(" ansible collection location = %s" % ':'.join(C.COLLECTIONS_PATHS))
317 result.append(" executable location = %s" % sys.argv[0])
318 result.append(" python version = %s (%s)" % (''.join(sys.version.splitlines()), to_native(sys.executable)))
319 result.append(f" jinja version = {_templating.jinja2_version}")
320 result.append(f" pyyaml version = {yaml.__version__} ({libyaml_fragment})")
321
322 return "\n".join(result)
323
324
325 #
326 # Functions to add pre-canned options to an OptionParser
327 #
328
329 def create_base_parser(prog, desc=None, epilog=None):
330 """
331 Create an options parser for all ansible scripts
332 """
333 # base opts
334 parser = ArgumentParser(
335 prog=prog,
336 formatter_class=SortingHelpFormatter,
337 epilog=epilog,
338 description=desc,
339 conflict_handler='resolve',
340 )
341 version_help = "show program's version number, config file location, configured module search path," \
342 " module location, executable location and exit"
343
344 parser.add_argument('--version', action=AnsibleVersion, nargs=0, help=version_help)
345 add_verbosity_options(parser)
346 return parser
347
348
349 def add_verbosity_options(parser):
350 """Add options for verbosity"""
351 parser.add_argument('-v', '--verbose', dest='verbosity', default=C.DEFAULT_VERBOSITY, action="count",
352 help="Causes Ansible to print more debug messages. Adding multiple -v will increase the verbosity, "
353 "the builtin plugins currently evaluate up to -vvvvvv. A reasonable level to start is -vvv, "
354 "connection debugging might require -vvvv.")
355
356
357 def add_async_options(parser):
358 """Add options for commands which can launch async tasks"""
359 parser.add_argument('-P', '--poll', default=C.DEFAULT_POLL_INTERVAL, type=int, dest='poll_interval',
360 help="set the poll interval if using -B (default=%s)" % C.DEFAULT_POLL_INTERVAL)
361 parser.add_argument('-B', '--background', dest='seconds', type=int, default=0,
362 help='run asynchronously, failing after X seconds (default=N/A)')
363
364
365 def add_basedir_options(parser):
366 """Add options for commands which can set a playbook basedir"""
367 parser.add_argument('--playbook-dir', default=C.PLAYBOOK_DIR, dest='basedir', action='store',
368 help="Since this tool does not use playbooks, use this as a substitute playbook directory. "
369 "This sets the relative path for many features including roles/ group_vars/ etc.",
370 type=unfrack_path())
371
372
373 def add_check_options(parser):
374 """Add options for commands which can run with diagnostic information of tasks"""
375 parser.add_argument("-C", "--check", default=False, dest='check', action='store_true',
376 help="don't make any changes; instead, try to predict some of the changes that may occur")
377 parser.add_argument("-D", "--diff", default=C.DIFF_ALWAYS, dest='diff', action='store_true',
378 help="when changing (small) files and templates, show the differences in those"
379 " files; works great with --check")
380
381
382 def add_connect_options(parser):
383 """Add options for commands which need to connection to other hosts"""
384 connect_group = parser.add_argument_group("Connection Options", "control as whom and how to connect to hosts")
385
386 connect_group.add_argument('--private-key', '--key-file', default=C.DEFAULT_PRIVATE_KEY_FILE, dest='private_key_file',
387 help='use this file to authenticate the connection', type=unfrack_path())
388 connect_group.add_argument('-u', '--user', default=C.DEFAULT_REMOTE_USER, dest='remote_user',
389 help='connect as this user (default=%s)' % C.DEFAULT_REMOTE_USER)
390 connect_group.add_argument('-c', '--connection', dest='connection', default=C.DEFAULT_TRANSPORT,
391 help="connection type to use (default=%s)" % C.DEFAULT_TRANSPORT)
392 connect_group.add_argument('-T', '--timeout', default=None, type=int, dest='timeout',
393 help="override the connection timeout in seconds (default depends on connection)")
394
395 # ssh only
396 connect_group.add_argument('--ssh-common-args', default=None, dest='ssh_common_args',
397 help="specify common arguments to pass to sftp/scp/ssh (e.g. ProxyCommand)")
398 connect_group.add_argument('--sftp-extra-args', default=None, dest='sftp_extra_args',
399 help="specify extra arguments to pass to sftp only (e.g. -f, -l)")
400 connect_group.add_argument('--scp-extra-args', default=None, dest='scp_extra_args',
401 help="specify extra arguments to pass to scp only (e.g. -l)")
402 connect_group.add_argument('--ssh-extra-args', default=None, dest='ssh_extra_args',
403 help="specify extra arguments to pass to ssh only (e.g. -R)")
404
405 parser.add_argument_group(connect_group)
406
407 connect_password_group = parser.add_mutually_exclusive_group()
408 connect_password_group.add_argument('-k', '--ask-pass', default=C.DEFAULT_ASK_PASS, dest='ask_pass', action='store_true',
409 help='ask for connection password')
410 connect_password_group.add_argument('--connection-password-file', '--conn-pass-file', default=C.CONNECTION_PASSWORD_FILE, dest='connection_password_file',
411 help="Connection password file", type=unfrack_path(), action='store')
412
413 parser.add_argument_group(connect_password_group)
414
415
416 def add_fork_options(parser):
417 """Add options for commands that can fork worker processes"""
418 parser.add_argument('-f', '--forks', dest='forks', default=C.DEFAULT_FORKS, type=int,
419 help="specify number of parallel processes to use (default=%s)" % C.DEFAULT_FORKS)
420
421
422 def add_inventory_options(parser):
423 """Add options for commands that utilize inventory"""
424 parser.add_argument('-i', '--inventory', '--inventory-file', dest='inventory', action="append",
425 help="specify inventory host path or comma separated host list",
426 deprecated=DeprecatedArgument(version='2.23', option='--inventory-file', alternatives="-i or --inventory"))
427 parser.add_argument('--list-hosts', dest='listhosts', action='store_true',
428 help='outputs a list of matching hosts; does not execute anything else')
429 parser.add_argument('-l', '--limit', default=C.DEFAULT_SUBSET, dest='subset',
430 help='further limit selected hosts to an additional pattern')
431 parser.add_argument('--flush-cache', dest='flush_cache', action='store_true',
432 help="clear the fact cache for every host in inventory")
433
434
435 def add_meta_options(parser):
436 """Add options for commands which can launch meta tasks from the command line"""
437 parser.add_argument('--force-handlers', default=C.DEFAULT_FORCE_HANDLERS, dest='force_handlers', action='store_true',
438 help="run handlers even if a task fails")
439
440
441 def add_module_options(parser):
442 """Add options for commands that load modules"""
443 module_path = C.config.get_configuration_definition('DEFAULT_MODULE_PATH').get('default', '')
444 parser.add_argument('-M', '--module-path', dest='module_path', default=None,
445 help="prepend colon-separated path(s) to module library (default=%s)" % module_path,
446 type=unfrack_path(pathsep=True), action=PrependListAction)
447
448
449 def add_output_options(parser):
450 """Add options for commands which can change their output"""
451 parser.add_argument('-o', '--one-line', dest='one_line', action='store_true', help='condense output',
452 deprecated=DeprecatedArgument(version='2.23', alternatives='callback configuration to enable the oneline callback'))
453 parser.add_argument('-t', '--tree', dest='tree', default=None, help='log output to this directory',
454 deprecated=DeprecatedArgument(version='2.23', alternatives='callback configuration to enable the tree callback'))
455
456
457 def add_runas_options(parser):
458 """
459 Add options for commands which can run tasks as another user
460
461 Note that this includes the options from add_runas_prompt_options(). Only one of these
462 functions should be used.
463 """
464 runas_group = parser.add_argument_group("Privilege Escalation Options", "control how and which user you become as on target hosts")
465
466 # consolidated privilege escalation (become)
467 runas_group.add_argument("-b", "--become", default=C.DEFAULT_BECOME, action="store_true", dest='become',
468 help="run operations with become (does not imply password prompting)")
469 runas_group.add_argument('--become-method', dest='become_method', default=C.DEFAULT_BECOME_METHOD,
470 help='privilege escalation method to use (default=%s)' % C.DEFAULT_BECOME_METHOD +
471 ', use `ansible-doc -t become -l` to list valid choices.')
472 runas_group.add_argument('--become-user', default=None, dest='become_user', type=str,
473 help='run operations as this user (default=%s)' % C.DEFAULT_BECOME_USER)
474
475 parser.add_argument_group(runas_group)
476
477 add_runas_prompt_options(parser)
478
479
480 def add_runas_prompt_options(parser, runas_group=None):
481 """
482 Add options for commands which need to prompt for privilege escalation credentials
483
484 Note that add_runas_options() includes these options already. Only one of the two functions
485 should be used.
486 """
487 if runas_group is not None:
488 parser.add_argument_group(runas_group)
489
490 runas_pass_group = parser.add_mutually_exclusive_group()
491
492 runas_pass_group.add_argument('-K', '--ask-become-pass', dest='become_ask_pass', action='store_true',
493 default=C.DEFAULT_BECOME_ASK_PASS,
494 help='ask for privilege escalation password')
495 runas_pass_group.add_argument('--become-password-file', '--become-pass-file', default=C.BECOME_PASSWORD_FILE, dest='become_password_file',
496 help="Become password file", type=unfrack_path(), action='store')
497
498 parser.add_argument_group(runas_pass_group)
499
500
501 def add_runtask_options(parser):
502 """Add options for commands that run a task"""
503 parser.add_argument('-e', '--extra-vars', dest="extra_vars", action="append", type=maybe_unfrack_path('@'),
504 help="set additional variables as key=value or YAML/JSON, if filename prepend with @", default=[])
505
506
507 def add_tasknoplay_options(parser):
508 """Add options for commands that run a task w/o a defined play"""
509 parser.add_argument('--task-timeout', type=int, dest="task_timeout", action="store", default=C.TASK_TIMEOUT,
510 help="set task timeout limit in seconds, must be positive integer.")
511
512
513 def add_subset_options(parser):
514 """Add options for commands which can run a subset of tasks"""
515 parser.add_argument('-t', '--tags', dest='tags', default=C.TAGS_RUN, action='append',
516 help="only run plays and tasks tagged with these values")
517 parser.add_argument('--skip-tags', dest='skip_tags', default=C.TAGS_SKIP, action='append',
518 help="only run plays and tasks whose tags do not match these values")
519
520
521 def add_vault_options(parser):
522 """Add options for loading vault files"""
523 parser.add_argument('--vault-id', default=[], dest='vault_ids', action='append', type=str,
524 help='the vault identity to use')
525 base_group = parser.add_mutually_exclusive_group()
526 base_group.add_argument('-J', '--ask-vault-password', '--ask-vault-pass', default=C.DEFAULT_ASK_VAULT_PASS, dest='ask_vault_pass', action='store_true',
527 help='ask for vault password')
528 base_group.add_argument('--vault-password-file', '--vault-pass-file', default=[], dest='vault_password_files',
529 help="vault password file", type=unfrack_path(follow=False), action='append')
530
531
532 def _tagged_type_factory(name: str, func: t.Callable[[str], object], /) -> t.Callable[[str], object]:
533 """
534 Return a callable that wraps the given function.
535 The result of the wrapped function will be tagged with Origin.
536 It will also be tagged with TrustedAsTemplate if it is equal to the original input string.
537 """
538 def tag_value(value: str) -> object:
539 result = func(value)
540
541 if result is value or func is str:
542 # Values which are not mutated are automatically trusted for templating.
543 # The `is` reference equality is critically important, as other types may only alter the tags, so object equality is
544 # not sufficient to prevent them being tagged as trusted when they should not.
545 # Explicitly include all usages using the `str` type factory since it strips tags.
546 result = TrustedAsTemplate().tag(result)
547
548 if not (origin := Origin.get_tag(value)):
549 origin = Origin(description=f'<CLI option {name!r}>')
550
551 return origin.tag(result)
552
553 tag_value._name = name # simplify debugging by attaching the argument name to the function
554
555 return tag_value