Debian Codegraph @

lib/ansible/cli/config.py

raw ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 #!/usr/bin/env python
2 # Copyright: (c) 2017, Ansible Project
3 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
4 # PYTHON_ARGCOMPLETE_OK
5
6 from __future__ import annotations
7
8 # ansible.cli needs to be imported first, to ensure the source bin/* scripts run that code first
9 from ansible.cli import CLI
10
11 import os
12 import shlex
13 import sys
14 import yaml
15
16 from collections.abc import Mapping
17
18 from ansible import context
19 import ansible.plugins.loader as plugin_loader
20
21 from ansible import constants as C
22 from ansible.cli.arguments import option_helpers as opt_help
23 from ansible.config.manager import ConfigManager
24 from ansible.errors import AnsibleError, AnsibleOptionsError, AnsibleRequiredOptionError
25 from ansible.module_utils.common.text.converters import to_native, to_text, to_bytes
26 from ansible._internal import _json
27 from ansible.parsing.quoting import is_quoted
28 from ansible.parsing.yaml.dumper import AnsibleDumper
29 from ansible.utils.color import stringc
30 from ansible.utils.display import Display
31 from ansible.utils.path import unfrackpath
32
33 display = Display()
34
35
36 _IGNORE_CHANGED = frozenset({'_terms', '_input'})
37
38
39 def yaml_dump(data, default_flow_style=False, default_style=None):
40 return yaml.dump(data, Dumper=AnsibleDumper, default_flow_style=default_flow_style, default_style=default_style)
41
42
43 def yaml_short(data):
44 return yaml_dump(data, default_flow_style=True, default_style="''")
45
46
47 def get_constants():
48 """ helper method to ensure we can template based on existing constants """
49 if not hasattr(get_constants, 'cvars'):
50 get_constants.cvars = {k: getattr(C, k) for k in dir(C) if not k.startswith('__')}
51 return get_constants.cvars
52
53
54 def _ansible_env_vars(varname):
55 """ return true or false depending if variable name is possibly a 'configurable' ansible env variable """
56 return all(
57 [
58 varname.startswith("ANSIBLE_"),
59 not varname.startswith(("ANSIBLE_TEST_", "ANSIBLE_LINT_")),
60 varname not in ("ANSIBLE_CONFIG", "ANSIBLE_DEV_HOME"),
61 ]
62 )
63
64
65 def _get_evar_list(settings):
66 data = []
67 for setting in settings:
68 if 'env' in settings[setting] and settings[setting]['env']:
69 for varname in settings[setting]['env']:
70 data.append(varname.get('name'))
71 return data
72
73
74 def _get_ini_entries(settings):
75 data = {}
76 for setting in settings:
77 if 'ini' in settings[setting] and settings[setting]['ini']:
78 for kv in settings[setting]['ini']:
79 if not kv['section'] in data:
80 data[kv['section']] = set()
81 data[kv['section']].add(kv['key'])
82 return data
83
84
85 class ConfigCLI(CLI):
86 """ Config command line class """
87
88 name = 'ansible-config'
89
90 def __init__(self, args, callback=None):
91
92 self.config_file = None
93 self.config = None
94 super(ConfigCLI, self).__init__(args, callback)
95
96 def init_parser(self):
97
98 super(ConfigCLI, self).init_parser(
99 desc="View ansible configuration.",
100 )
101
102 common = opt_help.ArgumentParser(add_help=False)
103 opt_help.add_verbosity_options(common)
104 common.add_argument('-c', '--config', dest='config_file',
105 help="path to configuration file, defaults to first file found in precedence.")
106 common.add_argument("-t", "--type", action="store", default='all', dest='type',
107 choices=['all', 'base'] + list(C.CONFIGURABLE_PLUGINS),
108 help="Filter down to a specific plugin type. Defaults to 'all'; use 'base' for the previous behavior.")
109 common.add_argument('args', help='Specific plugin to target, requires type of plugin to be set', nargs='*')
110
111 subparsers = self.parser.add_subparsers(dest='action')
112 subparsers.required = True
113
114 list_parser = subparsers.add_parser('list', help='Print all config options', parents=[common])
115 list_parser.set_defaults(func=self.execute_list)
116 list_parser.add_argument('--format', '-f', dest='format', action='store', choices=['json', 'yaml'], default='yaml',
117 help='Output format for list')
118
119 dump_parser = subparsers.add_parser('dump', help='Dump configuration', parents=[common])
120 dump_parser.set_defaults(func=self.execute_dump)
121 dump_parser.add_argument('--only-changed', '--changed-only', dest='only_changed', action='store_true',
122 help="Only show configurations that have changed from the default")
123 dump_parser.add_argument('--format', '-f', dest='format', action='store', choices=['json', 'yaml', 'display'], default='display',
124 help='Output format for dump')
125
126 view_parser = subparsers.add_parser('view', help='View configuration file', parents=[common])
127 view_parser.set_defaults(func=self.execute_view)
128
129 init_parser = subparsers.add_parser('init', help='Create initial configuration', parents=[common])
130 init_parser.set_defaults(func=self.execute_init)
131 init_parser.add_argument('--format', '-f', dest='format', action='store', choices=['ini', 'env', 'vars'], default='ini',
132 help='Output format for init')
133 init_parser.add_argument('--disabled', dest='commented', action='store_true', default=False,
134 help='Prefixes all entries with a comment character to disable them')
135
136 validate_parser = subparsers.add_parser('validate',
137 help='Validate the configuration file and environment variables. '
138 'By default it checks the base settings and all installed plugins (use -t to narrow down).',
139 parents=[common])
140 validate_parser.set_defaults(func=self.execute_validate)
141 validate_parser.add_argument('--format', '-f', dest='format', action='store', choices=['ini', 'env'] , default='ini',
142 help='Output format for init')
143
144 def post_process_args(self, options):
145 options = super(ConfigCLI, self).post_process_args(options)
146 display.verbosity = options.verbosity
147
148 return options
149
150 def run(self):
151
152 super(ConfigCLI, self).run()
153
154 # initialize each galaxy server's options from known listed servers
155 self._galaxy_servers = [s for s in C.GALAXY_SERVER_LIST or [] if s] # clean list, reused later here
156 C.config.load_galaxy_server_defs(self._galaxy_servers)
157
158 if context.CLIARGS['config_file']:
159 self.config_file = unfrackpath(context.CLIARGS['config_file'], follow=False)
160 b_config = to_bytes(self.config_file)
161 if os.path.exists(b_config) and os.access(b_config, os.R_OK):
162 self.config = ConfigManager(self.config_file)
163 else:
164 raise AnsibleOptionsError('The provided configuration file is missing or not accessible: %s' % to_native(self.config_file))
165 else:
166 self.config = C.config
167 self.config_file = self.config._config_file
168
169 if self.config_file:
170 try:
171 if not os.path.exists(self.config_file):
172 raise AnsibleOptionsError("%s does not exist or is not accessible" % (self.config_file))
173 elif not os.path.isfile(self.config_file):
174 raise AnsibleOptionsError("%s is not a valid file" % (self.config_file))
175
176 os.environ['ANSIBLE_CONFIG'] = to_native(self.config_file)
177 except Exception:
178 if context.CLIARGS['action'] in ['view']:
179 raise
180
181 elif context.CLIARGS['action'] == 'view':
182 raise AnsibleError('Invalid or no config file was supplied')
183
184 # run the requested action
185 context.CLIARGS['func']()
186
187 def execute_view(self):
188 """
189 Displays the current config file
190 """
191 try:
192 with open(self.config_file, 'rb') as f:
193 self.pager(to_text(f.read(), errors='surrogate_or_strict'))
194 except Exception as e:
195 raise AnsibleError("Failed to open config file: %s" % to_native(e))
196
197 def _list_plugin_settings(self, ptype, plugins=None):
198 entries = {}
199 loader = getattr(plugin_loader, '%s_loader' % ptype)
200
201 # build list
202 if plugins:
203 plugin_cs = []
204 for plugin in plugins:
205 p = loader.get(plugin, class_only=True)
206 if p is None:
207 display.warning("Skipping %s as we could not find matching plugin" % plugin)
208 else:
209 plugin_cs.append(p)
210 else:
211 plugin_cs = loader.all(class_only=True)
212
213 # iterate over class instances
214 for plugin in plugin_cs:
215 finalname = name = plugin._load_name
216 if name.startswith('_'):
217 # alias or deprecated
218 if os.path.islink(plugin._original_path):
219 continue
220 else:
221 finalname = name.replace('_', '', 1) + ' (DEPRECATED)'
222
223 entries[finalname] = self.config.get_configuration_definitions(ptype, name)
224
225 return entries
226
227 def _list_entries_from_args(self):
228 """
229 build a dict with the list requested configs
230 """
231
232 config_entries = {}
233 if context.CLIARGS['type'] in ('base', 'all'):
234 # this dumps main/common configs
235 config_entries = self.config.get_configuration_definitions(ignore_private=True)
236
237 # for base and all, we include galaxy servers
238 config_entries['GALAXY_SERVERS'] = {}
239 for server in self._galaxy_servers:
240 config_entries['GALAXY_SERVERS'][server] = self.config.get_configuration_definitions('galaxy_server', server)
241
242 if context.CLIARGS['type'] != 'base':
243 config_entries['PLUGINS'] = {}
244
245 if context.CLIARGS['type'] == 'all':
246 # now each plugin type
247 for ptype in C.CONFIGURABLE_PLUGINS:
248 config_entries['PLUGINS'][ptype.upper()] = self._list_plugin_settings(ptype)
249 elif context.CLIARGS['type'] != 'base':
250 # only for requested types
251 config_entries['PLUGINS'][context.CLIARGS['type']] = self._list_plugin_settings(context.CLIARGS['type'], context.CLIARGS['args'])
252
253 return config_entries
254
255 def execute_list(self):
256 """
257 list and output available configs
258 """
259
260 config_entries = self._list_entries_from_args()
261 if context.CLIARGS['format'] == 'yaml':
262 output = yaml_dump(config_entries)
263 elif context.CLIARGS['format'] == 'json':
264 output = _json.json_dumps_formatted(config_entries)
265
266 self.pager(to_text(output, errors='surrogate_or_strict'))
267
268 def _get_settings_vars(self, settings, subkey):
269
270 data = []
271 if context.CLIARGS['commented']:
272 prefix = '#'
273 else:
274 prefix = ''
275
276 for setting in settings:
277
278 if not settings[setting].get('description'):
279 continue
280
281 default = self.config.template_default(settings[setting].get('default', ''), get_constants())
282 if subkey == 'env':
283 stype = settings[setting].get('type', '')
284 if stype == 'boolean':
285 if default:
286 default = '1'
287 else:
288 default = '0'
289 elif default:
290 if stype == 'list':
291 if not isinstance(default, str):
292 # python lists are not valid env ones
293 try:
294 default = ', '.join(default)
295 except Exception as e:
296 # list of other stuff
297 default = '%s' % to_native(default)
298 if isinstance(default, str) and not is_quoted(default):
299 default = shlex.quote(default)
300 elif default is None:
301 default = ''
302
303 if subkey in settings[setting] and settings[setting][subkey]:
304 entry = settings[setting][subkey][-1]['name']
305 if isinstance(settings[setting]['description'], str):
306 desc = settings[setting]['description']
307 else:
308 desc = '\n#'.join(settings[setting]['description'])
309 name = settings[setting].get('name', setting)
310 data.append('# %s(%s): %s' % (name, settings[setting].get('type', 'string'), desc))
311
312 # TODO: might need quoting and value coercion depending on type
313 if subkey == 'env':
314 if entry.startswith('_ANSIBLE_'):
315 continue
316 data.append('%s%s=%s' % (prefix, entry, default))
317 elif subkey == 'vars':
318 if entry.startswith('_ansible_'):
319 continue
320 data.append(prefix + '%s: %s' % (entry, to_text(yaml_short(default), errors='surrogate_or_strict')))
321 data.append('')
322
323 return data
324
325 def _get_settings_ini(self, settings, seen):
326
327 sections = {}
328 for o in sorted(settings.keys()):
329
330 opt = settings[o]
331
332 if not isinstance(opt, Mapping):
333 # recursed into one of the few settings that is a mapping, now hitting it's strings
334 continue
335
336 if not opt.get('description'):
337 # its a plugin
338 new_sections = self._get_settings_ini(opt, seen)
339 for s in new_sections:
340 if s in sections:
341 sections[s].extend(new_sections[s])
342 else:
343 sections[s] = new_sections[s]
344 continue
345
346 if isinstance(opt['description'], str):
347 desc = '# (%s) %s' % (opt.get('type', 'string'), opt['description'])
348 else:
349 desc = "# (%s) " % opt.get('type', 'string')
350 desc += "\n# ".join(opt['description'])
351
352 if 'ini' in opt and opt['ini']:
353 entry = opt['ini'][-1]
354 if entry['section'] not in seen:
355 seen[entry['section']] = []
356 if entry['section'] not in sections:
357 sections[entry['section']] = []
358
359 # avoid dupes
360 if entry['key'] not in seen[entry['section']]:
361 seen[entry['section']].append(entry['key'])
362
363 default = self.config.template_default(opt.get('default', ''), get_constants())
364 if opt.get('type', '') == 'list' and not isinstance(default, str):
365 # python lists are not valid ini ones
366 default = ', '.join(default)
367 elif default is None:
368 default = ''
369
370 if context.CLIARGS.get('commented', False):
371 entry['key'] = ';%s' % entry['key']
372
373 key = desc + '\n%s=%s' % (entry['key'], default)
374
375 sections[entry['section']].append(key)
376
377 return sections
378
379 def execute_init(self):
380 """Create initial configuration"""
381
382 seen = {}
383 data = []
384 config_entries = self._list_entries_from_args()
385 plugin_types = config_entries.pop('PLUGINS', None)
386
387 if context.CLIARGS['format'] == 'ini':
388 sections = self._get_settings_ini(config_entries, seen)
389
390 if plugin_types:
391 for ptype in plugin_types:
392 plugin_sections = self._get_settings_ini(plugin_types[ptype], seen)
393 for s in plugin_sections:
394 if s in sections:
395 sections[s].extend(plugin_sections[s])
396 else:
397 sections[s] = plugin_sections[s]
398
399 if sections:
400 for section in sections.keys():
401 data.append('[%s]' % section)
402 for key in sections[section]:
403 data.append(key)
404 data.append('')
405 data.append('')
406
407 elif context.CLIARGS['format'] in ('env', 'vars'): # TODO: add yaml once that config option is added
408 data = self._get_settings_vars(config_entries, context.CLIARGS['format'])
409 if plugin_types:
410 for ptype in plugin_types:
411 for plugin in plugin_types[ptype].keys():
412 data.extend(self._get_settings_vars(plugin_types[ptype][plugin], context.CLIARGS['format']))
413
414 self.pager(to_text('\n'.join(data), errors='surrogate_or_strict'))
415
416 def _render_settings(self, config):
417
418 entries = []
419 for setting in sorted(config):
420 changed = (config[setting]['origin'] not in ('default', 'REQUIRED') and setting not in _IGNORE_CHANGED)
421
422 if context.CLIARGS['format'] == 'display':
423 if isinstance(config[setting], dict):
424 # proceed normally
425 value = config[setting]['value']
426 if config[setting]['origin'] == 'default' or setting in _IGNORE_CHANGED:
427 color = 'green'
428 value = self.config.template_default(value, get_constants())
429 elif config[setting]['origin'] == 'REQUIRED':
430 # should include '_terms', '_input', etc
431 color = 'red'
432 else:
433 color = 'yellow'
434 msg = "%s(%s) = %s" % (setting, config[setting]['origin'], value)
435 else:
436 color = 'green'
437 msg = "%s(%s) = %s" % (setting, 'default', config[setting].get('default'))
438
439 entry = stringc(msg, color)
440 else:
441 entry = {}
442 for key in config[setting].keys():
443 if key == 'type':
444 continue
445 entry[key] = config[setting][key]
446
447 if not context.CLIARGS['only_changed'] or changed:
448 entries.append(entry)
449
450 return entries
451
452 def _get_global_configs(self):
453
454 # Add base
455 config = self.config.get_configuration_definitions(ignore_private=True)
456 # convert to settings
457 settings = {}
458 for setting in config.keys():
459 v, o = C.config.get_config_value_and_origin(setting, cfile=self.config_file, variables=get_constants())
460 settings[setting] = {
461 'name': setting,
462 'value': v,
463 'origin': o,
464 'type': None
465 }
466
467 return self._render_settings(settings)
468
469 def _get_plugin_configs(self, ptype, plugins):
470
471 # prep loading
472 loader = getattr(plugin_loader, '%s_loader' % ptype)
473
474 # accumulators
475 output = []
476 config_entries = {}
477
478 # build list
479 if plugins:
480 plugin_cs = []
481 for plugin in plugins:
482 p = loader.get(plugin, class_only=True)
483 if p is None:
484 display.warning("Skipping %s as we could not find matching plugin" % plugin)
485 else:
486 plugin_cs.append(loader.get(plugin, class_only=True))
487 else:
488 plugin_cs = loader.all(class_only=True)
489
490 for plugin in plugin_cs:
491 # in case of deprecation they diverge
492 finalname = name = plugin._load_name
493 if name.startswith('_'):
494 if os.path.islink(plugin._original_path):
495 # skip alias
496 continue
497 # deprecated, but use 'nice name'
498 finalname = name.replace('_', '', 1) + ' (DEPRECATED)'
499
500 # default entries per plugin
501 config_entries[finalname] = self.config.get_configuration_definitions(ptype, name)
502
503 try:
504 # populate config entries by loading plugin
505 dump = loader.get(name, class_only=True)
506 except Exception as e:
507 display.warning('Skipping "%s" %s plugin, as we cannot load plugin to check config due to : %s' % (name, ptype, to_native(e)))
508 continue
509
510 # actually get the values
511 for setting in config_entries[finalname].keys():
512 try:
513 v, o = C.config.get_config_value_and_origin(setting, cfile=self.config_file, plugin_type=ptype, plugin_name=name, variables=get_constants())
514 except AnsibleRequiredOptionError:
515 v = None
516 o = 'REQUIRED'
517
518 if v is None and o is None:
519 # not all cases will be error
520 o = 'REQUIRED'
521
522 config_entries[finalname][setting] = {
523 'name': setting,
524 'value': v,
525 'origin': o,
526 'type': None
527 }
528
529 # pretty please!
530 results = self._render_settings(config_entries[finalname])
531 if results:
532 if context.CLIARGS['format'] == 'display':
533 # avoid header for empty lists (only changed!)
534 output.append('\n%s:\n%s' % (finalname, '_' * len(finalname)))
535 output.extend(results)
536 else:
537 output.append({finalname: results})
538
539 return output
540
541 def _get_galaxy_server_configs(self):
542
543 output = []
544 # add galaxy servers
545 for server in self._galaxy_servers:
546 server_config = {}
547 s_config = self.config.get_configuration_definitions('galaxy_server', server)
548 for setting in s_config.keys():
549 try:
550 v, o = C.config.get_config_value_and_origin(setting, plugin_type='galaxy_server', plugin_name=server, cfile=self.config_file)
551 except AnsibleError as e:
552 if s_config[setting].get('required', False):
553 v = None
554 o = 'REQUIRED'
555 else:
556 raise e
557 if v is None and o is None:
558 # not all cases will be error
559 o = 'REQUIRED'
560 server_config[setting] = {
561 'name': setting,
562 'value': v,
563 'origin': o,
564 'type': None
565 }
566 if context.CLIARGS['format'] == 'display':
567 if not context.CLIARGS['only_changed'] or server_config:
568 equals = '=' * len(server)
569 output.append(f'\n{server}\n{equals}')
570 output.extend(self._render_settings(server_config))
571 else:
572 output.append({server: server_config})
573
574 return output
575
576 def execute_dump(self):
577 """
578 Shows the current settings, merges ansible.cfg if specified
579 """
580 output = []
581 if context.CLIARGS['type'] in ('base', 'all'):
582 # deal with base
583 output = self._get_global_configs()
584
585 # add galaxy servers
586 server_config_list = self._get_galaxy_server_configs()
587 if context.CLIARGS['format'] == 'display':
588 output.append('\nGALAXY_SERVERS:\n')
589 output.extend(server_config_list)
590 else:
591 configs = {}
592 for server_config in server_config_list:
593 server = list(server_config.keys())[0]
594 server_reduced_config = server_config.pop(server)
595 configs[server] = list(server_reduced_config.values())
596 output.append({'GALAXY_SERVERS': configs})
597
598 if context.CLIARGS['type'] == 'all':
599 # add all plugins
600 for ptype in C.CONFIGURABLE_PLUGINS:
601 plugin_list = self._get_plugin_configs(ptype, context.CLIARGS['args'])
602 if context.CLIARGS['format'] == 'display':
603 if not context.CLIARGS['only_changed'] or plugin_list:
604 output.append('\n%s:\n%s' % (ptype.upper(), '=' * len(ptype)))
605 output.extend(plugin_list)
606 else:
607 if ptype in ('modules', 'doc_fragments'):
608 pname = ptype.upper()
609 else:
610 pname = '%s_PLUGINS' % ptype.upper()
611 output.append({pname: plugin_list})
612
613 elif context.CLIARGS['type'] != 'base':
614 # deal with specific plugin
615 output = self._get_plugin_configs(context.CLIARGS['type'], context.CLIARGS['args'])
616
617 if context.CLIARGS['format'] == 'display':
618 text = '\n'.join(output)
619 if context.CLIARGS['format'] == 'yaml':
620 text = yaml_dump(output)
621 elif context.CLIARGS['format'] == 'json':
622 text = _json.json_dumps_formatted(output)
623
624 self.pager(to_text(text, errors='surrogate_or_strict'))
625
626 def execute_validate(self):
627
628 found = False
629 config_entries = self._list_entries_from_args()
630 plugin_types = config_entries.pop('PLUGINS', None)
631 galaxy_servers = config_entries.pop('GALAXY_SERVERS', None)
632
633 if context.CLIARGS['format'] == 'ini':
634 if C.CONFIG_FILE is not None:
635 # validate ini config since it is found
636
637 sections = _get_ini_entries(config_entries)
638 # Also from plugins
639 if plugin_types:
640 for ptype in plugin_types:
641 for plugin in plugin_types[ptype].keys():
642 plugin_sections = _get_ini_entries(plugin_types[ptype][plugin])
643 for s in plugin_sections:
644 if s in sections:
645 sections[s].update(plugin_sections[s])
646 else:
647 sections[s] = plugin_sections[s]
648 if galaxy_servers:
649 for server in galaxy_servers:
650 server_sections = _get_ini_entries(galaxy_servers[server])
651 for s in server_sections:
652 if s in sections:
653 sections[s].update(server_sections[s])
654 else:
655 sections[s] = server_sections[s]
656 if sections:
657 p = C.config._parsers[C.CONFIG_FILE]
658 for s in p.sections():
659 # check for valid sections
660 if s not in sections:
661 display.error(f"Found unknown section '{s}' in '{C.CONFIG_FILE}.")
662 found = True
663 continue
664
665 # check keys in valid sections
666 for k in p.options(s):
667 if k not in sections[s]:
668 display.error(f"Found unknown key '{k}' in section '{s}' in '{C.CONFIG_FILE}.")
669 found = True
670
671 elif context.CLIARGS['format'] == 'env':
672 # validate any 'ANSIBLE_' env vars found
673 evars = [varname for varname in os.environ.keys() if _ansible_env_vars(varname)]
674 if evars:
675 data = _get_evar_list(config_entries)
676 if plugin_types:
677 for ptype in plugin_types:
678 for plugin in plugin_types[ptype].keys():
679 data.extend(_get_evar_list(plugin_types[ptype][plugin]))
680
681 for evar in evars:
682 if evar not in data:
683 display.error(f"Found unknown environment variable '{evar}'.")
684 found = True
685
686 # we found discrepancies!
687 if found:
688 sys.exit(1)
689
690 # allsgood
691 display.display("All configurations seem valid!")
692
693
694 def main(args=None):
695 ConfigCLI.cli_executor(args)
696
697
698 if __name__ == '__main__':
699 main()