Debian Codegraph @

lib/ansible/cli/__init__.py

raw
1 # Copyright: (c) 2012-2014, Michael DeHaan <[email protected]>
2 # Copyright: (c) 2016, Toshio Kuratomi <[email protected]>
3 # Copyright: (c) 2018, Ansible Project
4 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
5
6 from __future__ import annotations
7
8 import locale
9 import os
10 import sys
11
12 # We overload the ``ansible`` adhoc command to provide the functionality for
13 # ``SSH_ASKPASS``. This code is here, and not in ``adhoc.py`` to bypass
14 # unnecessary code. The program provided to ``SSH_ASKPASS`` can only be invoked
15 # as a singular command, ``python -m`` doesn't work for that use case, and we
16 # aren't adding a new entrypoint at this time. Assume that if we are executing
17 # and there is only a single item in argv plus the executable, and the env var
18 # is set we are in ``SSH_ASKPASS`` mode
19 if 1 <= len(sys.argv) <= 2 and os.path.basename(sys.argv[0]) == "ansible" and os.getenv('_ANSIBLE_SSH_ASKPASS_SHM'):
20 from ansible.cli import _ssh_askpass
21 _ssh_askpass.main()
22
23
24 # Used for determining if the system is running a new enough python version
25 # and should only restrict on our documented minimum versions
26 _PY_MIN = (3, 13)
27
28 if sys.version_info < _PY_MIN:
29 raise SystemExit(
30 f"ERROR: Ansible requires Python {'.'.join(map(str, _PY_MIN))} or newer on the controller. "
31 f"Current version: {''.join(sys.version.splitlines())}"
32 )
33
34
35 def check_blocking_io():
36 """Check stdin/stdout/stderr to make sure they are using blocking IO."""
37 handles = []
38
39 for handle in (sys.stdin, sys.stdout, sys.stderr):
40 # noinspection PyBroadException
41 try:
42 fd = handle.fileno()
43 except Exception:
44 continue # not a real file handle, such as during the import sanity test
45
46 if not os.get_blocking(fd):
47 handles.append(getattr(handle, 'name', None) or '#%s' % fd)
48
49 if handles:
50 raise SystemExit('ERROR: Ansible requires blocking IO on stdin/stdout/stderr. '
51 'Non-blocking file handles detected: %s' % ', '.join(_io for _io in handles))
52
53
54 check_blocking_io()
55
56
57 def initialize_locale():
58 """Set the locale to the users default setting and ensure
59 the locale and filesystem encoding are UTF-8.
60 """
61 try:
62 locale.setlocale(locale.LC_ALL, '')
63 dummy, encoding = locale.getlocale()
64 except (locale.Error, ValueError) as e:
65 raise SystemExit(
66 'ERROR: Ansible could not initialize the preferred locale: %s' % e
67 )
68
69 if not encoding or encoding.lower() not in ('utf-8', 'utf8'):
70 raise SystemExit('ERROR: Ansible requires the locale encoding to be UTF-8; Detected %s.' % encoding)
71
72 fs_enc = sys.getfilesystemencoding()
73 if fs_enc.lower() != 'utf-8':
74 raise SystemExit('ERROR: Ansible requires the filesystem encoding to be UTF-8; Detected %s.' % fs_enc)
75
76
77 initialize_locale()
78
79
80 import getpass
81 import subprocess
82 import traceback
83 from abc import ABC, abstractmethod
84 from pathlib import Path
85
86 from ansible import _internal # do not remove or defer; ensures controller-specific state is set early
87
88 _internal.setup()
89
90 from ansible.errors import AnsibleError, ExitCode
91
92 try:
93 from ansible import constants as C
94 from ansible.utils.display import Display
95 display = Display()
96 except Exception as ex:
97 if isinstance(ex, AnsibleError):
98 ex_msg = ' '.join((ex.message, ex._help_text or '')).strip()
99 else:
100 ex_msg = str(ex)
101
102 print(f'ERROR: {ex_msg}\n\n{"".join(traceback.format_exception(ex))}', file=sys.stderr)
103 sys.exit(5)
104
105
106 from ansible import context
107 from ansible.utils import display as _display
108 from ansible.cli.arguments import option_helpers as opt_help
109 from ansible.inventory.manager import InventoryManager
110 from ansible.module_utils.common.text.converters import to_bytes, to_text
111 from ansible.module_utils.common.collections import is_sequence
112 from ansible.module_utils.common.file import is_executable
113 from ansible.module_utils.secrets import register_secret
114 from ansible.parsing.dataloader import DataLoader
115 from ansible.parsing.vault import PromptVaultSecret, get_file_vault_secret, VaultSecretsContext
116 from ansible.plugins.loader import add_all_plugin_dirs, init_plugin_loader
117 from ansible.release import __version__
118 from ansible.utils.collection_loader import AnsibleCollectionConfig
119 from ansible.utils.collection_loader._collection_finder import _get_collection_name_from_path
120 from ansible.utils.path import unfrackpath
121 from ansible.vars.manager import VariableManager
122 from ansible.module_utils._internal import _deprecator
123 from ansible._internal._secret_input import load_secret_input_files
124 from ansible._internal._ssh import _agent_launch
125
126
127 try:
128 import argcomplete
129 HAS_ARGCOMPLETE = True
130 except ImportError:
131 HAS_ARGCOMPLETE = False
132
133
134 class CLI(ABC):
135 """ code behind bin/ansible* programs """
136
137 PAGER = C.config.get_config_value('PAGER')
138
139 # -F (quit-if-one-screen) -R (allow raw ansi control chars)
140 # -S (chop long lines) -X (disable termcap init and de-init)
141 LESS_OPTS = 'FRSX'
142 SKIP_INVENTORY_DEFAULTS = False
143 USES_CONNECTION = False
144
145 def __init__(self, args, callback=None):
146 """
147 Base init method for all command line programs
148 """
149
150 if not args:
151 raise ValueError('A non-empty list for args is required')
152
153 self.args = args
154 self.parser = None
155 self.callback = callback
156
157 self.show_devel_warning()
158
159 def show_devel_warning(self) -> None:
160 if C.DEVEL_WARNING and __version__.endswith('dev0'):
161 display.warning(
162 'You are running the development version of Ansible. You should only run Ansible from "devel" if '
163 'you are modifying the Ansible engine, or trying out features under development. This is a rapidly '
164 'changing source of code and can become unstable at any point.'
165 )
166
167 @abstractmethod
168 def run(self):
169 """Run the ansible command
170
171 Subclasses must implement this method. It does the actual work of
172 running an Ansible command.
173 """
174 self.parse()
175
176 # Register pre-seeded secrets as early as possible so they are masked from any subsequent output.
177 if self.name in ('ansible', 'ansible-playbook', 'ansible-console'):
178 load_secret_input_files(C.config.get_config_value('_SECRETS_INPUT_FILES'))
179
180 # Initialize plugin loader after parse, so that the init code can utilize parsed arguments
181 cli_collections_path = context.CLIARGS.get('collections_path') or []
182 if not is_sequence(cli_collections_path):
183 # In some contexts ``collections_path`` is singular
184 cli_collections_path = [cli_collections_path]
185 init_plugin_loader(cli_collections_path)
186
187 display.vv(to_text(opt_help.version(self.parser.prog)))
188
189 if C.CONFIG_FILE:
190 display.v(u"Using %s as config file" % to_text(C.CONFIG_FILE))
191 else:
192 display.v(u"No config file found; using defaults")
193
194 _display._report_config_warnings(_deprecator.ANSIBLE_CORE_DEPRECATOR)
195
196 @staticmethod
197 def split_vault_id(vault_id):
198 # return (before_@, after_@)
199 # if no @, return whole string as after_
200 if '@' not in vault_id:
201 return (None, vault_id)
202
203 parts = vault_id.split('@', 1)
204 ret = tuple(parts)
205 return ret
206
207 @staticmethod
208 def build_vault_ids(vault_ids, vault_password_files=None,
209 ask_vault_pass=None, auto_prompt=True):
210 vault_password_files = vault_password_files or []
211 vault_ids = vault_ids or []
212
213 # convert vault_password_files into vault_ids slugs
214 for password_file in vault_password_files:
215 id_slug = u'%s@%s' % (C.DEFAULT_VAULT_IDENTITY, password_file)
216
217 # note this makes --vault-id higher precedence than --vault-password-file
218 # if we want to intertwingle them in order probably need a cli callback to populate vault_ids
219 # used by --vault-id and --vault-password-file
220 vault_ids.append(id_slug)
221
222 # if an action needs an encrypt password (create_new_password=True) and we don't
223 # have other secrets setup, then automatically add a password prompt as well.
224 # prompts can't/shouldn't work without a tty, so don't add prompt secrets
225 if ask_vault_pass or (not vault_ids and auto_prompt):
226
227 id_slug = u'%s@%s' % (C.DEFAULT_VAULT_IDENTITY, u'prompt_ask_vault_pass')
228 vault_ids.append(id_slug)
229
230 return vault_ids
231
232 @staticmethod
233 def setup_vault_secrets(loader, vault_ids, vault_password_files=None,
234 ask_vault_pass=None, create_new_password=False,
235 auto_prompt=True, initialize_context=True):
236 # list of tuples
237 vault_secrets = []
238
239 # Depending on the vault_id value (including how --ask-vault-pass / --vault-password-file create a vault_id)
240 # we need to show different prompts. This is for compat with older Towers that expect a
241 # certain vault password prompt format, so 'promp_ask_vault_pass' vault_id gets the old format.
242 prompt_formats = {}
243
244 # If there are configured default vault identities, they are considered 'first'
245 # so we prepend them to vault_ids (from cli) here
246
247 vault_password_files = vault_password_files or []
248 if C.DEFAULT_VAULT_PASSWORD_FILE:
249 vault_password_files.append(C.DEFAULT_VAULT_PASSWORD_FILE)
250
251 if create_new_password:
252 prompt_formats['prompt'] = ['New vault password (%(vault_id)s): ',
253 'Confirm new vault password (%(vault_id)s): ']
254 # 2.3 format prompts for --ask-vault-pass
255 prompt_formats['prompt_ask_vault_pass'] = ['New Vault password: ',
256 'Confirm New Vault password: ']
257 else:
258 prompt_formats['prompt'] = ['Vault password (%(vault_id)s): ']
259 # The format when we use just --ask-vault-pass needs to match 'Vault password:\s*?$'
260 prompt_formats['prompt_ask_vault_pass'] = ['Vault password: ']
261
262 vault_ids = CLI.build_vault_ids(vault_ids,
263 vault_password_files,
264 ask_vault_pass,
265 auto_prompt=auto_prompt)
266
267 last_exception = found_vault_secret = None
268 for vault_id_slug in vault_ids:
269 vault_id_name, vault_id_value = CLI.split_vault_id(vault_id_slug)
270 if vault_id_value in ['prompt', 'prompt_ask_vault_pass']:
271
272 # --vault-id some_name@prompt_ask_vault_pass --vault-id other_name@prompt_ask_vault_pass will be a little
273 # confusing since it will use the old format without the vault id in the prompt
274 built_vault_id = vault_id_name or C.DEFAULT_VAULT_IDENTITY
275
276 # choose the prompt based on --vault-id=prompt or --ask-vault-pass. --ask-vault-pass
277 # always gets the old format for Tower compatibility.
278 # ie, we used --ask-vault-pass, so we need to use the old vault password prompt
279 # format since Tower needs to match on that format.
280 prompted_vault_secret = PromptVaultSecret(prompt_formats=prompt_formats[vault_id_value],
281 vault_id=built_vault_id)
282
283 # a empty or invalid password from the prompt will warn and continue to the next
284 # without erroring globally
285 try:
286 prompted_vault_secret.load()
287 except AnsibleError as exc:
288 display.warning('Error in vault password prompt (%s): %s' % (vault_id_name, exc))
289 raise
290
291 found_vault_secret = True
292 vault_secrets.append((built_vault_id, prompted_vault_secret))
293
294 # update loader with new secrets incrementally, so we can load a vault password
295 # that is encrypted with a vault secret provided earlier
296 loader.set_vault_secrets(vault_secrets)
297 continue
298
299 # assuming anything else is a password file
300 display.vvvvv('Reading vault password file: %s' % vault_id_value)
301 # read vault_pass from a file
302 try:
303 file_vault_secret = get_file_vault_secret(filename=vault_id_value,
304 vault_id=vault_id_name,
305 loader=loader)
306 except AnsibleError as exc:
307 display.warning('Error getting vault password file (%s): %s' % (vault_id_name, to_text(exc)))
308 last_exception = exc
309 continue
310
311 try:
312 file_vault_secret.load()
313 except AnsibleError as exc:
314 display.warning('Error in vault password file loading (%s): %s' % (vault_id_name, to_text(exc)))
315 last_exception = exc
316 continue
317
318 found_vault_secret = True
319 if vault_id_name:
320 vault_secrets.append((vault_id_name, file_vault_secret))
321 else:
322 vault_secrets.append((C.DEFAULT_VAULT_IDENTITY, file_vault_secret))
323
324 # update loader with as-yet-known vault secrets
325 loader.set_vault_secrets(vault_secrets)
326
327 # An invalid or missing password file will error globally
328 # if no valid vault secret was found.
329 if last_exception and not found_vault_secret:
330 raise last_exception
331
332 if initialize_context:
333 VaultSecretsContext.initialize(VaultSecretsContext(vault_secrets))
334
335 return vault_secrets
336
337 @staticmethod
338 def _get_secret(prompt: str) -> str:
339 return getpass.getpass(prompt=prompt)
340
341 @staticmethod
342 def ask_passwords():
343 """ prompt for connection and become passwords if needed """
344
345 op = context.CLIARGS
346 sshpass = None
347 becomepass = None
348
349 become_prompt_method = "BECOME" if C.AGNOSTIC_BECOME_PROMPT else op['become_method'].upper()
350
351 try:
352 become_prompt = "%s password: " % become_prompt_method
353 if op['ask_pass']:
354 sshpass = CLI._get_secret("SSH password: ")
355 become_prompt = "%s password[defaults to SSH password]: " % become_prompt_method
356 elif op['connection_password_file']:
357 sshpass = CLI.get_password_from_file(op['connection_password_file'])
358
359 if op['become_ask_pass']:
360 becomepass = CLI._get_secret(become_prompt)
361 if op['ask_pass'] and becomepass == '':
362 becomepass = sshpass
363 elif op['become_password_file']:
364 becomepass = CLI.get_password_from_file(op['become_password_file'])
365
366 except EOFError:
367 pass
368
369 if sshpass:
370 register_secret(sshpass)
371
372 if becomepass:
373 register_secret(becomepass)
374
375 return sshpass, becomepass
376
377 def validate_conflicts(self, op, runas_opts=False, fork_opts=False):
378 """ check for conflicting options """
379
380 if fork_opts:
381 if op.forks < 1:
382 self.parser.error("The number of processes (--forks) must be >= 1")
383
384 return op
385
386 @abstractmethod
387 def init_parser(self, desc=None, epilog=None):
388 """
389 Create an options parser for most ansible scripts
390
391 Subclasses need to implement this method. They will usually call the base class's
392 init_parser to create a basic version and then add their own options on top of that.
393
394 An implementation will look something like this::
395
396 def init_parser(self):
397 super(MyCLI, self).init_parser(desc='The purpose of the program is...')
398 ansible.arguments.option_helpers.add_runas_options(self.parser)
399 self.parser.add_option('--my-option', dest='my_option', action='store')
400 """
401 self.parser = opt_help.create_base_parser(self.name, desc=desc, epilog=epilog)
402
403 @abstractmethod
404 def post_process_args(self, options):
405 """Process the command line args
406
407 Subclasses need to implement this method. This method validates and transforms the command
408 line arguments. It can be used to check whether conflicting values were given, whether filenames
409 exist, etc.
410
411 An implementation will look something like this::
412
413 def post_process_args(self, options):
414 options = super(MyCLI, self).post_process_args(options)
415 if options.addition and options.subtraction:
416 raise AnsibleOptionsError('Only one of --addition and --subtraction can be specified')
417 if isinstance(options.listofhosts, str):
418 options.listofhosts = options.listofhosts.split(',')
419 return options
420 """
421
422 # process tags
423 if hasattr(options, 'tags') and not options.tags:
424 # optparse defaults does not do what's expected
425 # More specifically, we want `--tags` to be additive. So we cannot
426 # simply change C.TAGS_RUN's default to ["all"] because then passing
427 # --tags foo would cause us to have ['all', 'foo']
428 options.tags = ['all']
429 if hasattr(options, 'tags') and options.tags:
430 tags = set()
431 for tag_set in options.tags:
432 for tag in tag_set.split(u','):
433 tags.add(tag.strip())
434 options.tags = list(tags)
435
436 # process skip_tags
437 if hasattr(options, 'skip_tags') and options.skip_tags:
438 skip_tags = set()
439 for tag_set in options.skip_tags:
440 for tag in tag_set.split(u','):
441 skip_tags.add(tag.strip())
442 options.skip_tags = list(skip_tags)
443
444 # Make sure path argument doesn't have a backslash
445 if hasattr(options, 'action') and options.action in ['install', 'download'] and hasattr(options, 'args'):
446 options.args = [path.rstrip("/") for path in options.args]
447
448 # process inventory options except for CLIs that require their own processing
449 if hasattr(options, 'inventory') and not self.SKIP_INVENTORY_DEFAULTS:
450
451 if options.inventory:
452
453 # should always be list
454 if isinstance(options.inventory, str):
455 options.inventory = [options.inventory]
456
457 # Ensure full paths when needed
458 options.inventory = [unfrackpath(opt, follow=False) if ',' not in opt else opt for opt in options.inventory]
459 else:
460 options.inventory = C.DEFAULT_HOST_LIST
461
462 return options
463
464 def parse(self):
465 """Parse the command line args
466
467 This method parses the command line arguments. It uses the parser
468 stored in the self.parser attribute and saves the args and options in
469 context.CLIARGS.
470
471 Subclasses need to implement two helper methods, init_parser() and post_process_args() which
472 are called from this function before and after parsing the arguments.
473 """
474 self.init_parser()
475
476 if HAS_ARGCOMPLETE:
477 argcomplete.autocomplete(self.parser)
478
479 try:
480 options = self.parser.parse_args(self.args[1:])
481 except SystemExit as ex:
482 if ex.code != 0:
483 self.parser.exit(status=2, message=" \n%s" % self.parser.format_help())
484 raise
485 options = self.post_process_args(options)
486 context._init_global_context(options)
487
488 @staticmethod
489 def version_info(gitinfo=False):
490 """ return full ansible version info """
491 if gitinfo:
492 # expensive call, user with care
493 ansible_version_string = opt_help.version()
494 else:
495 ansible_version_string = __version__
496 ansible_version = ansible_version_string.split()[0]
497 ansible_versions = ansible_version.split('.')
498 for counter in range(len(ansible_versions)):
499 if ansible_versions[counter] == "":
500 ansible_versions[counter] = 0
501 try:
502 ansible_versions[counter] = int(ansible_versions[counter])
503 except Exception:
504 pass
505 if len(ansible_versions) < 3:
506 for counter in range(len(ansible_versions), 3):
507 ansible_versions.append(0)
508 return {'string': ansible_version_string.strip(),
509 'full': ansible_version,
510 'major': ansible_versions[0],
511 'minor': ansible_versions[1],
512 'revision': ansible_versions[2]}
513
514 @staticmethod
515 def pager(text):
516 """ find reasonable way to display text """
517 # this is a much simpler form of what is in pydoc.py
518 if not sys.stdout.isatty():
519 display.display(text, screen_only=True)
520 elif CLI.PAGER:
521 if sys.platform == 'win32':
522 display.display(text, screen_only=True)
523 else:
524 CLI.pager_pipe(text)
525 else:
526 p = subprocess.Popen('less --version', shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
527 p.communicate()
528 if p.returncode == 0:
529 CLI.pager_pipe(text, pager='less')
530 else:
531 display.display(text, screen_only=True)
532
533 @staticmethod
534 def pager_pipe(text, pager=None):
535 """ pipe text through a pager """
536 pager_cmd = pager or CLI.PAGER
537
538 if 'less' in pager_cmd:
539 os.environ['LESS'] = CLI.LESS_OPTS
540 try:
541 cmd = subprocess.Popen(pager_cmd, shell=True, stdin=subprocess.PIPE, stdout=sys.stdout)
542 cmd.communicate(input=to_bytes(text))
543 except (OSError, KeyboardInterrupt):
544 pass
545
546 def _play_prereqs(self):
547 # TODO: evaluate moving all of the code that touches ``AnsibleCollectionConfig``
548 # into ``init_plugin_loader`` so that we can specifically remove
549 # ``AnsibleCollectionConfig.playbook_paths`` to make it immutable after instantiation
550
551 options = context.CLIARGS
552
553 # all needs loader
554 loader = DataLoader()
555
556 basedir = options.get('basedir', False)
557 if basedir:
558 loader.set_basedir(basedir)
559 add_all_plugin_dirs(basedir)
560 AnsibleCollectionConfig.playbook_paths = basedir
561 default_collection = _get_collection_name_from_path(basedir)
562 if default_collection:
563 display.warning(u'running with default collection {0}'.format(default_collection))
564 AnsibleCollectionConfig.default_collection = default_collection
565
566 vault_ids = list(options['vault_ids'])
567 default_vault_ids = C.DEFAULT_VAULT_IDENTITY_LIST
568 vault_ids = default_vault_ids + vault_ids
569
570 vault_secrets = CLI.setup_vault_secrets(loader,
571 vault_ids=vault_ids,
572 vault_password_files=list(options['vault_password_files']),
573 ask_vault_pass=options['ask_vault_pass'],
574 auto_prompt=False)
575 loader.set_vault_secrets(vault_secrets)
576
577 if self.USES_CONNECTION:
578 _agent_launch.launch_ssh_agent()
579
580 # create the inventory, and filter it based on the subset specified (if any)
581 inventory = InventoryManager(loader=loader, sources=options['inventory'], cache=(not options.get('flush_cache')))
582
583 # create the variable manager, which will be shared throughout
584 # the code, ensuring a consistent view of global variables
585 variable_manager = VariableManager(loader=loader, inventory=inventory, version_info=CLI.version_info(gitinfo=False))
586
587 # flush fact cache if requested
588 if options['flush_cache']:
589 CLI._flush_cache(inventory, variable_manager)
590
591 return loader, inventory, variable_manager
592
593 @staticmethod
594 def _flush_cache(inventory, variable_manager):
595 variable_manager.clear_facts('localhost')
596 for host in inventory.list_hosts():
597 hostname = host.get_name()
598 variable_manager.clear_facts(hostname)
599
600 @staticmethod
601 def get_host_list(inventory, subset, pattern='all'):
602
603 no_hosts = False
604 if len(inventory.list_hosts()) == 0:
605 # Empty inventory
606 if C.LOCALHOST_WARNING and pattern not in C.LOCALHOST:
607 display.warning("provided hosts list is empty, only localhost is available. Note that the implicit localhost does not match 'all'")
608 no_hosts = True
609
610 inventory.subset(subset)
611
612 hosts = inventory.list_hosts(pattern)
613 if not hosts and no_hosts is False:
614 raise AnsibleError("Specified inventory, host pattern and/or --limit leaves us with no hosts to target.")
615
616 return hosts
617
618 @staticmethod
619 def get_password_from_file(pwd_file: str) -> str:
620 b_pwd_file = to_bytes(pwd_file)
621
622 if b_pwd_file == b'-':
623 # ensure its read as bytes
624 secret = sys.stdin.buffer.read()
625
626 elif not os.path.exists(b_pwd_file):
627 raise AnsibleError("The password file %s was not found" % pwd_file)
628
629 elif is_executable(b_pwd_file):
630 display.vvvv(u'The password file %s is a script.' % to_text(pwd_file))
631 cmd = [b_pwd_file]
632
633 try:
634 p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
635 except OSError as e:
636 raise AnsibleError("Problem occurred when trying to run the password script %s (%s)."
637 " If this is not a script, remove the executable bit from the file." % (pwd_file, e))
638
639 stdout, stderr = p.communicate()
640 if p.returncode != 0:
641 raise AnsibleError("The password script %s returned an error (rc=%s): %s" % (pwd_file, p.returncode, to_text(stderr)))
642 secret = stdout
643
644 else:
645 try:
646 with open(b_pwd_file, "rb") as password_file:
647 secret = password_file.read().strip()
648 except OSError as ex:
649 raise AnsibleError(f"Could not read password file {pwd_file!r}.") from ex
650
651 secret = secret.strip(b'\r\n')
652
653 if not secret:
654 raise AnsibleError('Empty password was provided from file (%s)' % pwd_file)
655
656 return to_text(secret)
657
658 @classmethod
659 def cli_executor(cls, args=None):
660 if args is None:
661 args = sys.argv
662
663 try:
664 display.debug("starting run")
665
666 ansible_dir = Path(C.ANSIBLE_HOME).expanduser()
667 try:
668 ansible_dir.mkdir(mode=0o700, exist_ok=True)
669 except OSError as ex:
670 display.error_as_warning(f"Failed to create the directory {ansible_dir!r}.", ex)
671 else:
672 display.debug("Created the '%s' directory" % ansible_dir)
673
674 cli = cls(args)
675 exit_code = cli.run()
676 except AnsibleError as ex:
677 display.error(ex)
678 exit_code = ex._exit_code
679 except KeyboardInterrupt:
680 display.error("User interrupted execution")
681 exit_code = ExitCode.KEYBOARD_INTERRUPT
682 except Exception as ex:
683 try:
684 raise AnsibleError("Unexpected Exception, this is probably a bug.") from ex
685 except AnsibleError as ex2:
686 # DTFIX-FUTURE: clean this up so we're not hacking the internals- re-wrap in an AnsibleCLIUnhandledError that always shows TB, or?
687 from ansible.module_utils._internal import _traceback
688 _traceback._is_traceback_enabled = lambda *_args, **_kwargs: True
689 display.error(ex2)
690 exit_code = ExitCode.UNKNOWN_ERROR
691
692 sys.exit(exit_code)