Debian Codegraph @

bin/ansible-console

raw symbols SCIP
1 #!/usr/bin/env python3
2 # Copyright: (c) 2014, Nandor Sivok <[email protected]>
3 # Copyright: (c) 2016, Redhat Inc
4 # Copyright: (c) 2018, Ansible Project
5 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
6 # PYTHON_ARGCOMPLETE_OK
7
8 from __future__ import annotations
9
10 # ansible.cli needs to be imported first, to ensure the source bin/* scripts run that code first
11 from ansible.cli import CLI
12
13 import atexit
14 import cmd
15 import getpass
16 import readline
17 import os
18 import sys
19
20 from ansible import constants as C
21 from ansible import context
22 from ansible.cli.arguments import option_helpers as opt_help
23 from ansible.executor.task_queue_manager import AnsibleEndPlay, TaskQueueManager
24 from ansible.module_utils.common.text.converters import to_native, to_text
25 from ansible.module_utils.parsing.convert_bool import boolean
26 from ansible.parsing.splitter import parse_kv
27 from ansible.playbook.play import Play
28 from ansible.plugins.list import list_plugins
29 from ansible.plugins.loader import module_loader, fragment_loader
30 from ansible.utils import plugin_docs
31 from ansible.utils.color import stringc
32 from ansible._internal._datatag._tags import TrustedAsTemplate
33 from ansible.utils.display import Display
34
35 display = Display()
36
37
38 class ConsoleCLI(CLI, cmd.Cmd):
39 """
40 A REPL that allows for running ad-hoc tasks against a chosen inventory
41 from a nice shell with built-in tab completion (based on dominis'
42 ``ansible-shell``).
43
44 It supports several commands, and you can modify its configuration at
45 runtime:
46
47 - ``cd [pattern]``: change host/group
48 (you can use host patterns eg.: ``app*.dc*:!app01*``)
49 - ``list``: list available hosts in the current path
50 - ``list groups``: list groups included in the current path
51 - ``become``: toggle the become flag
52 - ``!``: forces shell module instead of the ansible module
53 (``!yum update -y``)
54 - ``verbosity [num]``: set the verbosity level
55 - ``forks [num]``: set the number of forks
56 - ``become_user [user]``: set the become_user
57 - ``remote_user [user]``: set the remote_user
58 - ``become_method [method]``: set the privilege escalation method
59 - ``check [bool]``: toggle check mode
60 - ``diff [bool]``: toggle diff mode
61 - ``timeout [integer]``: set the timeout of tasks in seconds
62 (0 to disable)
63 - ``help [command/module]``: display documentation for
64 the command or module
65 - ``exit``: exit ``ansible-console``
66 """
67
68 name = 'ansible-console'
69 modules = [] # type: list[str] | None
70 ARGUMENTS = {'host-pattern': 'A name of a group in the inventory, a shell-like glob '
71 'selecting hosts in inventory or any combination of the two separated by commas.'}
72
73 # use specific to console, but fallback to highlight for backwards compatibility
74 NORMAL_PROMPT = C.COLOR_CONSOLE_PROMPT or C.COLOR_HIGHLIGHT
75
76 USES_CONNECTION = True
77
78 def __init__(self, args):
79
80 super(ConsoleCLI, self).__init__(args)
81
82 self.intro = 'Welcome to the ansible console. Type help or ? to list commands.\n'
83
84 self.groups = []
85 self.hosts = []
86 self.pattern = None
87 self.variable_manager = None
88 self.loader = None
89 self.passwords = dict()
90
91 self.cwd = '*'
92
93 # Defaults for these are set from the CLI in run()
94 self.remote_user = None
95 self.become = None
96 self.become_user = None
97 self.become_method = None
98 self.check_mode = None
99 self.diff = None
100 self.forks = None
101 self.task_timeout = None
102 self.collections = None
103
104 cmd.Cmd.__init__(self)
105
106 def init_parser(self):
107 super(ConsoleCLI, self).init_parser(
108 desc="REPL console for executing Ansible tasks.",
109 epilog="This is not a live session/connection: each task is executed in the background and returns its results."
110 )
111 opt_help.add_runas_options(self.parser)
112 opt_help.add_inventory_options(self.parser)
113 opt_help.add_connect_options(self.parser)
114 opt_help.add_check_options(self.parser)
115 opt_help.add_vault_options(self.parser)
116 opt_help.add_fork_options(self.parser)
117 opt_help.add_module_options(self.parser)
118 opt_help.add_basedir_options(self.parser)
119 opt_help.add_runtask_options(self.parser)
120 opt_help.add_tasknoplay_options(self.parser)
121
122 # options unique to shell
123 self.parser.add_argument('pattern', help='host pattern', metavar='pattern', default='all', nargs='?')
124 self.parser.add_argument('--step', dest='step', action='store_true',
125 help="one-step-at-a-time: confirm each task before running")
126
127 def post_process_args(self, options):
128 options = super(ConsoleCLI, self).post_process_args(options)
129 display.verbosity = options.verbosity
130 self.validate_conflicts(options, runas_opts=True, fork_opts=True)
131 return options
132
133 def get_names(self):
134 return dir(self)
135
136 def cmdloop(self):
137 try:
138 cmd.Cmd.cmdloop(self)
139
140 except KeyboardInterrupt:
141 self.cmdloop()
142
143 except EOFError:
144 self.display("[Ansible-console was exited]")
145 self.do_exit(self)
146
147 def set_prompt(self):
148 login_user = self.remote_user or getpass.getuser()
149 self.selected = self.inventory.list_hosts(self.cwd)
150 prompt = "%s@%s (%d)[f:%s]" % (login_user, self.cwd, len(self.selected), self.forks)
151 if self.become and self.become_user in [None, 'root']:
152 prompt += "# "
153 color = C.COLOR_ERROR
154 else:
155 prompt += "$ "
156 color = self.NORMAL_PROMPT
157 self.prompt = stringc(prompt, color, wrap_nonvisible_chars=True)
158
159 def list_modules(self):
160 return list_plugins('module', self.collections)
161
162 def default(self, line, forceshell=False):
163 """ actually runs modules """
164 if line.startswith("#"):
165 return False
166
167 if not self.cwd:
168 display.error("No host found")
169 return False
170
171 # defaults
172 module = 'shell'
173 module_args = line
174
175 if forceshell is not True:
176 possible_module, *possible_args = line.split()
177 if module_loader.find_plugin(possible_module):
178 # we found module!
179 module = possible_module
180 if possible_args:
181 module_args = ' '.join(possible_args)
182 else:
183 module_args = ''
184
185 module_args = TrustedAsTemplate().tag(module_args)
186
187 if self.callback:
188 cb = self.callback
189 elif C.DEFAULT_LOAD_CALLBACK_PLUGINS and C.DEFAULT_STDOUT_CALLBACK != 'default':
190 cb = C.DEFAULT_STDOUT_CALLBACK
191 else:
192 cb = 'minimal'
193
194 result = None
195 try:
196 check_raw = module in C._ACTION_ALLOWS_RAW_ARGS
197 task = dict(action=module, args=parse_kv(module_args, check_raw=check_raw), timeout=self.task_timeout)
198 play_ds = dict(
199 name="Ansible Shell",
200 hosts=self.cwd,
201 gather_facts='no',
202 tasks=[task],
203 remote_user=self.remote_user,
204 become=self.become,
205 become_user=self.become_user,
206 become_method=self.become_method,
207 check_mode=self.check_mode,
208 diff=self.diff,
209 collections=self.collections,
210 )
211 play = Play().load(play_ds, variable_manager=self.variable_manager, loader=self.loader)
212 except Exception as e:
213 display.error(u"Unable to build command: %s" % to_text(e))
214 return False
215
216 try:
217 # now create a task queue manager to execute the play
218 self._tqm = None
219 try:
220 self._tqm = TaskQueueManager(
221 inventory=self.inventory,
222 variable_manager=self.variable_manager,
223 loader=self.loader,
224 passwords=self.passwords,
225 stdout_callback_name=cb,
226 run_additional_callbacks=C.DEFAULT_LOAD_CALLBACK_PLUGINS,
227 run_tree=False,
228 forks=self.forks,
229 )
230
231 result = self._tqm.run(play)
232 display.debug(result)
233 except AnsibleEndPlay as e:
234 result = e.result
235 finally:
236 if self._tqm:
237 self._tqm.cleanup()
238 if self.loader:
239 self.loader.cleanup_all_tmp_files()
240
241 if result is None:
242 display.error("No hosts found")
243 return False
244 except KeyboardInterrupt:
245 display.error('User interrupted execution')
246 return False
247 except Exception as ex:
248 display.error(ex)
249 return False
250
251 def emptyline(self):
252 return
253
254 def do_shell(self, arg):
255 """
256 You can run shell commands through the shell module.
257
258 eg.:
259 shell ps uax | grep java | wc -l
260 shell killall python
261 shell halt -n
262
263 You can use the ! to force the shell module. eg.:
264 !ps aux | grep java | wc -l
265 """
266 self.default(arg, True)
267
268 def help_shell(self):
269 display.display("You can run shell commands through the shell module.")
270
271 def do_forks(self, arg):
272 """Set the number of forks"""
273 if arg:
274 try:
275 forks = int(arg)
276 except TypeError:
277 display.error('Invalid argument for "forks"')
278 self.usage_forks()
279
280 if forks > 0:
281 self.forks = forks
282 self.set_prompt()
283
284 else:
285 display.display('forks must be greater than or equal to 1')
286 else:
287 self.usage_forks()
288
289 def help_forks(self):
290 display.display("Set the number of forks to use per task")
291 self.usage_forks()
292
293 def usage_forks(self):
294 display.display('Usage: forks <number>')
295
296 do_serial = do_forks
297 help_serial = help_forks
298
299 def do_collections(self, arg):
300 """Set list of collections for 'short name' usage"""
301 if arg in ('', 'none'):
302 self.collections = None
303 elif not arg:
304 self.usage_collections()
305 else:
306 collections = arg.split(',')
307 for collection in collections:
308 if self.collections is None:
309 self.collections = []
310 self.collections.append(collection.strip())
311
312 if self.collections:
313 display.v('Collections name search is set to: %s' % ', '.join(self.collections))
314 else:
315 display.v('Collections name search is using defaults')
316
317 def help_collections(self):
318 display.display("Set the collection name search path when using short names for plugins")
319 self.usage_collections()
320
321 def usage_collections(self):
322 display.display('Usage: collections <collection1>[, <collection2> ...]\n Use empty quotes or "none" to reset to default.\n')
323
324 def do_verbosity(self, arg):
325 """Set verbosity level"""
326 if not arg:
327 display.display('Usage: verbosity <number>')
328 else:
329 try:
330 display.verbosity = int(arg)
331 display.v('verbosity level set to %s' % arg)
332 except (TypeError, ValueError) as e:
333 display.error('The verbosity must be a valid integer: %s' % to_text(e))
334
335 def help_verbosity(self):
336 display.display("Set the verbosity level, equivalent to -v for 1 and -vvvv for 4.")
337
338 def do_cd(self, arg):
339 """
340 Change active host/group. You can use hosts patterns as well eg.:
341 cd webservers
342 cd webservers:dbservers
343 cd webservers:!phoenix
344 cd webservers:&staging
345 cd webservers:dbservers:&staging:!phoenix
346 """
347 if not arg:
348 self.cwd = '*'
349 elif arg in '/*':
350 self.cwd = 'all'
351 elif self.inventory.get_hosts(arg):
352 self.cwd = arg
353 else:
354 display.display("no host matched")
355
356 self.set_prompt()
357
358 def help_cd(self):
359 display.display("Change active host/group. ")
360 self.usage_cd()
361
362 def usage_cd(self):
363 display.display("Usage: cd <group>|<host>|<host pattern>")
364
365 def do_list(self, arg):
366 """List the hosts in the current group"""
367 if not arg:
368 for host in self.selected:
369 display.display(host.name)
370 elif arg == 'groups':
371 for group in self.groups:
372 display.display(group)
373 else:
374 display.error('Invalid option passed to "list"')
375 self.help_list()
376
377 def help_list(self):
378 display.display("List the hosts in the current group or a list of groups if you add 'groups'.")
379
380 def do_become(self, arg):
381 """Toggle whether plays run with become"""
382 if arg:
383 self.become = boolean(arg, strict=False)
384 display.v("become changed to %s" % self.become)
385 self.set_prompt()
386 else:
387 display.display("Please specify become value, e.g. `become yes`")
388
389 def help_become(self):
390 display.display("Toggle whether the tasks are run with become")
391
392 def do_remote_user(self, arg):
393 """Given a username, set the remote user plays are run by"""
394 if arg:
395 self.remote_user = arg
396 self.set_prompt()
397 else:
398 display.display("Please specify a remote user, e.g. `remote_user root`")
399
400 def help_remote_user(self):
401 display.display("Set the user for use as login to the remote target")
402
403 def do_become_user(self, arg):
404 """Given a username, set the user that plays are run by when using become"""
405 if arg:
406 self.become_user = arg
407 else:
408 display.display("Please specify a user, e.g. `become_user jenkins`")
409 display.v("Current user is %s" % self.become_user)
410 self.set_prompt()
411
412 def help_become_user(self):
413 display.display("Set the user for use with privilege escalation (which remote user attempts to 'become' when become is enabled)")
414
415 def do_become_method(self, arg):
416 """Given a become_method, set the privilege escalation method when using become"""
417 if arg:
418 self.become_method = arg
419 display.v("become_method changed to %s" % self.become_method)
420 else:
421 display.display("Please specify a become_method, e.g. `become_method su`")
422 display.v("Current become_method is %s" % self.become_method)
423
424 def help_become_method(self):
425 display.display("Set the privilege escalation plugin to use when become is enabled")
426
427 def do_check(self, arg):
428 """Toggle whether plays run with check mode"""
429 if arg:
430 self.check_mode = boolean(arg, strict=False)
431 display.display("check mode changed to %s" % self.check_mode)
432 else:
433 display.display("Please specify check mode value, e.g. `check yes`")
434 display.v("check mode is currently %s." % self.check_mode)
435
436 def help_check(self):
437 display.display("Toggle check_mode for the tasks")
438
439 def do_diff(self, arg):
440 """Toggle whether plays run with diff"""
441 if arg:
442 self.diff = boolean(arg, strict=False)
443 display.display("diff mode changed to %s" % self.diff)
444 else:
445 display.display("Please specify a diff value , e.g. `diff yes`")
446 display.v("diff mode is currently %s" % self.diff)
447
448 def help_diff(self):
449 display.display("Toggle diff output for the tasks")
450
451 def do_timeout(self, arg):
452 """Set the timeout"""
453 if arg:
454 try:
455 timeout = int(arg)
456 if timeout < 0:
457 display.error('The timeout must be greater than or equal to 1, use 0 to disable')
458 else:
459 self.task_timeout = timeout
460 except (TypeError, ValueError) as e:
461 display.error('The timeout must be a valid positive integer, or 0 to disable: %s' % to_text(e))
462 else:
463 self.usage_timeout()
464
465 def help_timeout(self):
466 display.display("Set task timeout in seconds")
467 self.usage_timeout()
468
469 def usage_timeout(self):
470 display.display('Usage: timeout <seconds>')
471
472 def do_exit(self, args):
473 """Exits from the console"""
474 sys.stdout.write('\nAnsible-console was exited.\n')
475 return -1
476
477 def help_exit(self):
478 display.display("LEAVE!")
479
480 do_EOF = do_exit
481 help_EOF = help_exit
482
483 def helpdefault(self, module_name):
484 if module_name:
485 in_path = module_loader.find_plugin(module_name)
486 if in_path:
487 oc, a, _dummy1, _dummy2 = plugin_docs.get_docstring(in_path, fragment_loader)
488 if oc:
489 display.display(oc['short_description'])
490 display.display('Parameters:')
491 for opt in oc['options'].keys():
492 display.display(' ' + stringc(opt, self.NORMAL_PROMPT) + ' ' + oc['options'][opt]['description'][0])
493 else:
494 display.error('No documentation found for %s.' % module_name)
495 else:
496 display.error('%s is not a valid command, use ? to list all valid commands.' % module_name)
497
498 def help_help(self):
499 display.warning("Don't be redundant!")
500
501 def complete_cd(self, text, line, begidx, endidx):
502 mline = line.partition(' ')[2]
503 offs = len(mline) - len(text)
504
505 if self.cwd in ('all', '*', '\\'):
506 completions = self.hosts + self.groups
507 else:
508 completions = [x.name for x in self.inventory.list_hosts(self.cwd)]
509
510 return [to_native(s)[offs:] for s in completions if to_native(s).startswith(to_native(mline))]
511
512 def completedefault(self, text, line, begidx, endidx):
513 if line.split()[0] in self.list_modules():
514 mline = line.split(' ')[-1]
515 offs = len(mline) - len(text)
516 completions = self.module_args(line.split()[0])
517
518 return [s[offs:] + '=' for s in completions if s.startswith(mline)]
519
520 def module_args(self, module_name):
521 in_path = module_loader.find_plugin(module_name)
522 oc, a, _dummy1, _dummy2 = plugin_docs.get_docstring(in_path, fragment_loader, is_module=True)
523 return list(oc['options'].keys())
524
525 def run(self):
526
527 super(ConsoleCLI, self).run()
528
529 sshpass = None
530 becomepass = None
531
532 # hosts
533 self.pattern = context.CLIARGS['pattern']
534 self.cwd = self.pattern
535
536 # Defaults from the command line
537 self.remote_user = context.CLIARGS['remote_user']
538 self.become = context.CLIARGS['become']
539 self.become_user = context.CLIARGS['become_user']
540 self.become_method = context.CLIARGS['become_method']
541 self.check_mode = context.CLIARGS['check']
542 self.diff = context.CLIARGS['diff']
543 self.forks = context.CLIARGS['forks']
544 self.task_timeout = context.CLIARGS['task_timeout']
545
546 # set module path if needed
547 if context.CLIARGS['module_path']:
548 for path in context.CLIARGS['module_path']:
549 if path:
550 module_loader.add_directory(path)
551
552 # dynamically add 'canonical' modules as commands, aliases could be used and dynamically loaded
553 self.modules = self.list_modules()
554 for module in self.modules:
555 setattr(self, 'do_' + module, lambda arg, module=module: self.default(module + ' ' + arg))
556 setattr(self, 'help_' + module, lambda module=module: self.helpdefault(module))
557
558 (sshpass, becomepass) = self.ask_passwords()
559 self.passwords = {'conn_pass': sshpass, 'become_pass': becomepass}
560
561 self.loader, self.inventory, self.variable_manager = self._play_prereqs()
562
563 hosts = self.get_host_list(self.inventory, context.CLIARGS['subset'], self.pattern)
564
565 self.groups = self.inventory.list_groups()
566 self.hosts = [x.name for x in hosts]
567
568 # This hack is to work around readline issues on a mac:
569 # http://stackoverflow.com/a/7116997/541202
570 if 'libedit' in readline.__doc__:
571 readline.parse_and_bind("bind ^I rl_complete")
572 else:
573 readline.parse_and_bind("tab: complete")
574
575 histfile = os.path.join(os.path.expanduser("~"), ".ansible-console_history")
576 try:
577 readline.read_history_file(histfile)
578 except OSError:
579 pass
580
581 atexit.register(readline.write_history_file, histfile)
582 self.set_prompt()
583 self.cmdloop()
584
585 def __getattr__(self, name):
586 """ handle not found to populate dynamically a module function if module matching name exists """
587 attr = None
588
589 if name.startswith('do_'):
590 module = name.replace('do_', '')
591 if module_loader.find_plugin(module):
592 setattr(self, name, lambda arg, module=module: self.default(module + ' ' + arg))
593 attr = object.__getattr__(self, name)
594 elif name.startswith('help_'):
595 module = name.replace('help_', '')
596 if module_loader.find_plugin(module):
597 setattr(self, name, lambda module=module: self.helpdefault(module))
598 attr = object.__getattr__(self, name)
599
600 if attr is None:
601 raise AttributeError(f"{self.__class__} does not have a {name} attribute")
602
603 return attr
604
605
606 def main(args=None):
607 ConsoleCLI.cli_executor(args)
608
609
610 if __name__ == '__main__':
611 main()