Debian Codegraph @

bin/ansible-config

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