Debian Codegraph @

lib/ansible/config/manager.py

raw
1 # Copyright: (c) 2017, 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 atexit
7 import decimal
8 import configparser
9 import functools
10 import os
11 import os.path
12 import sys
13 import stat
14 import tempfile
15 import typing as t
16
17 from collections.abc import Mapping, Sequence
18 from jinja2.nativetypes import NativeEnvironment
19
20 from ansible._internal._datatag import _tags
21 from ansible.errors import AnsibleOptionsError, AnsibleError, AnsibleUndefinedConfigEntry, AnsibleRequiredOptionError
22 from ansible.module_utils._internal._datatag import AnsibleTagHelper
23 from ansible.module_utils.common.sentinel import Sentinel
24 from ansible.module_utils.common.text.converters import to_text, to_bytes, to_native
25 from ansible.module_utils.common.yaml import yaml_load
26 from ansible.module_utils.parsing.convert_bool import boolean
27 from ansible.module_utils.secrets import register_secrets
28 from ansible.parsing.quoting import unquote
29 from ansible.utils.path import cleanup_tmp_file, makedirs_safe, unfrackpath
30
31 if t.TYPE_CHECKING:
32 from ansible.template import Templar
33
34
35 INTERNAL_DEFS = {'lookup': ('_terms',)}
36
37 GALAXY_SERVER_DEF = [
38 ('url', True, 'str'),
39 ('username', False, 'str'),
40 ('password', False, 'str'),
41 ('token', False, 'str'),
42 ('auth_url', False, 'str'),
43 ('validate_certs', False, 'bool'),
44 ('client_id', False, 'str'),
45 ('client_secret', False, 'str'),
46 ('timeout', False, 'int'),
47 ]
48
49 # config definition fields
50 GALAXY_SERVER_ADDITIONAL = {
51 'validate_certs': {'cli': [{'name': 'validate_certs'}]},
52 'timeout': {'cli': [{'name': 'timeout'}]},
53 'token': {'default': None},
54 }
55
56
57 # Config types eligible for `secret`; all resolve to a `str` or a sequence of `str`.
58 # Numeric/bool/dict types are excluded to avoid over-masking and unsupported source representations.
59 _SECRET_ALLOWED_TYPES = frozenset({'str', 'string', 'list'})
60
61
62 @t.runtime_checkable
63 class _EncryptedStringProtocol(t.Protocol):
64 """Protocol representing an `EncryptedString`, since it cannot be imported here."""
65 # DTFIX-FUTURE: collapse this with the one in collection loader, once we can
66
67 def _decrypt(self) -> str: ...
68
69
70 def _get_config_label(plugin_type: str, plugin_name: str, config: str) -> str:
71 """Return a label for the given config."""
72 entry = f'{config!r}'
73
74 if plugin_type:
75 entry += ' for'
76
77 if plugin_name:
78 entry += f' {plugin_name!r}'
79
80 entry += f' {plugin_type} plugin'
81
82 return entry
83
84
85 def _validate_secret_config_defs(
86 defs: Mapping[str, object],
87 plugin_type: str | None = None,
88 plugin_name: str | None = None,
89 ) -> None:
90 """Ensure any config definition marked `secret` uses a supported (string-producing) type."""
91 for config, cdef in defs.items():
92 if not isinstance(cdef, Mapping) or not cdef.get('secret'):
93 continue
94
95 value_type = cdef.get('type')
96
97 if not isinstance(value_type, str) or value_type.lower() not in _SECRET_ALLOWED_TYPES:
98 raise AnsibleOptionsError(
99 f"Config {_get_config_label(plugin_type, plugin_name, config)} cannot enable 'secret' with type {value_type!r}.",
100 help_text=f"'secret' is only supported for the following types: {', '.join(sorted(_SECRET_ALLOWED_TYPES))}.",
101 )
102
103
104 def ensure_type(value: object, value_type: str | None, origin: str | None = None, origin_ftype: str | None = None) -> t.Any:
105 """
106 Converts `value` to the requested `value_type`; raises `ValueError` for failed conversions.
107
108 Values for `value_type` are:
109
110 * boolean/bool: Return a `bool` by applying non-strict `bool` filter rules:
111 'y', 'yes', 'on', '1', 'true', 't', 1, 1.0, True return True, any other value is False.
112 * integer/int: Return an `int`. Accepts any `str` parseable by `int` or numeric value with a zero mantissa (including `bool`).
113 * float: Return a `float`. Accepts any `str` parseable by `float` or numeric value (including `bool`).
114 * list: Return a `list`. Accepts `list` or `Sequence`. Also accepts, `str`, splitting on ',' while stripping whitespace and unquoting items.
115 * none: Return `None`. Accepts only the string "None".
116 * path: Return a resolved path. Accepts `str`.
117 * temppath/tmppath/tmp: Return a unique temporary directory inside the resolved path specified by the value.
118 * pathspec: Return a `list` of resolved paths. Accepts a `list` or `Sequence`. Also accepts `str`, splitting on ':'.
119 * pathlist: Return a `list` of resolved paths. Accepts a `list` or `Sequence`. Also accepts `str`, splitting on `,` while stripping whitespace from paths.
120 * dictionary/dict: Return a `dict`. Accepts `dict` or `Mapping`.
121 * string/str: Return a `str`. Accepts `bool`, `int`, `float`, `complex` or `str`.
122
123 Path resolution ensures paths are `str` with expansion of '{{CWD}}', environment variables and '~'.
124 Non-absolute paths are expanded relative to the basedir from `origin`, if specified.
125
126 No conversion is performed if `value_type` is unknown or `value` is `None`.
127 When `origin_ftype` is "ini", a `str` result will be unquoted.
128 """
129
130 if value is None:
131 return None
132
133 original_value = value
134 copy_tags = value_type not in ('temppath', 'tmppath', 'tmp')
135
136 value = _ensure_type(value, value_type, origin)
137
138 if copy_tags and value is not original_value:
139 if isinstance(value, list):
140 value = [AnsibleTagHelper.tag_copy(original_value, item) for item in value]
141
142 value = AnsibleTagHelper.tag_copy(original_value, value)
143
144 if isinstance(value, str) and origin_ftype and origin_ftype == 'ini':
145 value = unquote(value)
146
147 return value
148
149
150 def _ensure_type(value: object, value_type: str | None, origin: str | None = None) -> t.Any:
151 """Internal implementation for `ensure_type`, call that function instead."""
152 original_value = value
153 basedir = origin if origin and os.path.isabs(origin) and os.path.exists(to_bytes(origin)) else None
154
155 if value_type:
156 value_type = value_type.lower()
157
158 match value_type:
159 case 'boolean' | 'bool':
160 return boolean(value, strict=False)
161
162 case 'integer' | 'int':
163 if isinstance(value, int): # handle both int and bool (which is an int)
164 return int(value)
165
166 if isinstance(value, (float, str)):
167 try:
168 # use Decimal for all other source type conversions; non-zero mantissa is a failure
169 if (decimal_value := decimal.Decimal(value)) == (int_part := int(decimal_value)):
170 return int_part
171 except (decimal.DecimalException, ValueError):
172 pass
173
174 case 'float':
175 if isinstance(value, float):
176 return value
177
178 if isinstance(value, (int, str)):
179 try:
180 return float(value)
181 except ValueError:
182 pass
183
184 case 'list':
185 if isinstance(value, list):
186 return value
187
188 if isinstance(value, str):
189 return [unquote(x.strip()) for x in value.split(',')]
190
191 if isinstance(value, Sequence) and not isinstance(value, bytes):
192 return list(value)
193
194 case 'none':
195 if value == "None":
196 return None
197
198 case 'path':
199 if isinstance(value, str):
200 return resolve_path(value, basedir=basedir)
201
202 case 'temppath' | 'tmppath' | 'tmp':
203 if isinstance(value, str):
204 value = resolve_path(value, basedir=basedir)
205
206 if not os.path.exists(value):
207 makedirs_safe(value, 0o700)
208
209 prefix = 'ansible-local-%s' % os.getpid()
210 value = tempfile.mkdtemp(prefix=prefix, dir=value)
211 atexit.register(cleanup_tmp_file, value, warn=True)
212
213 return value
214
215 case 'pathspec':
216 if isinstance(value, str):
217 value = value.split(os.pathsep)
218
219 if isinstance(value, Sequence) and not isinstance(value, bytes) and all(isinstance(x, str) for x in value):
220 return [resolve_path(x, basedir=basedir) for x in value]
221
222 case 'pathlist':
223 if isinstance(value, str):
224 value = [x.strip() for x in value.split(',')]
225
226 if isinstance(value, Sequence) and not isinstance(value, bytes) and all(isinstance(x, str) for x in value):
227 return [resolve_path(x, basedir=basedir) for x in value]
228
229 case 'dictionary' | 'dict':
230 if isinstance(value, dict):
231 return value
232
233 if isinstance(value, Mapping):
234 return dict(value)
235
236 case 'string' | 'str':
237 if isinstance(value, str):
238 return value
239
240 if isinstance(value, (bool, int, float, complex)):
241 return str(value)
242
243 if isinstance(value, _EncryptedStringProtocol):
244 return value._decrypt()
245
246 case _:
247 # FIXME: define and document a pass-through value_type (None, 'raw', 'object', '', ...) and then deprecate acceptance of unknown types
248 return value # return non-str values of unknown value_type as-is
249
250 raise ValueError(f'Invalid value provided for {value_type!r}: {original_value!r}.')
251
252
253 # FIXME: see if this can live in utils/path
254 def resolve_path(path: str, basedir: str | None = None) -> str:
255 """ resolve relative or 'variable' paths """
256 if '{{CWD}}' in path: # allow users to force CWD using 'magic' {{CWD}}
257 path = path.replace('{{CWD}}', os.getcwd())
258
259 return unfrackpath(path, follow=False, basedir=basedir)
260
261
262 # FIXME: generic file type?
263 def get_config_type(cfile):
264
265 ftype = None
266 if cfile is not None:
267 ext = os.path.splitext(cfile)[-1]
268 if ext in ('.ini', '.cfg'):
269 ftype = 'ini'
270 elif ext in ('.yaml', '.yml'):
271 ftype = 'yaml'
272 else:
273 raise AnsibleOptionsError("Unsupported configuration file extension for %s: %s" % (cfile, to_native(ext)))
274
275 return ftype
276
277
278 def find_ini_config_file(warnings=None):
279 """ Load INI Config File order(first found is used): ENV, CWD, HOME, /etc/ansible """
280 # FIXME: eventually deprecate ini configs
281
282 if warnings is None:
283 # Note: In this case, warnings does nothing
284 warnings = set()
285
286 potential_paths = []
287
288 # A value that can never be a valid path so that we can tell if ANSIBLE_CONFIG was set later
289 # We can't use None because we could set path to None.
290 # Environment setting
291 path_from_env = os.getenv("ANSIBLE_CONFIG", Sentinel)
292 if path_from_env is not Sentinel:
293 path_from_env = unfrackpath(path_from_env, follow=False)
294 if os.path.isdir(to_bytes(path_from_env)):
295 path_from_env = os.path.join(path_from_env, "ansible.cfg")
296 potential_paths.append(path_from_env)
297
298 # Current working directory
299 warn_cmd_public = False
300 try:
301 cwd = os.getcwd()
302 perms = os.stat(cwd)
303 cwd_cfg = os.path.join(cwd, "ansible.cfg")
304 if perms.st_mode & stat.S_IWOTH:
305 # Working directory is world writable so we'll skip it.
306 # Still have to look for a file here, though, so that we know if we have to warn
307 if os.path.exists(cwd_cfg):
308 warn_cmd_public = True
309 else:
310 potential_paths.append(to_text(cwd_cfg, errors='surrogate_or_strict'))
311 except OSError:
312 # If we can't access cwd, we'll simply skip it as a possible config source
313 pass
314
315 # Per user location
316 potential_paths.append(unfrackpath("~/.ansible.cfg", follow=False))
317
318 # System location
319 potential_paths.append("/etc/ansible/ansible.cfg")
320
321 for path in potential_paths:
322 b_path = to_bytes(path)
323 if os.path.exists(b_path) and os.access(b_path, os.R_OK):
324 break
325 else:
326 path = None
327
328 # Emit a warning if all the following are true:
329 # * We did not use a config from ANSIBLE_CONFIG
330 # * There's an ansible.cfg in the current working directory that we skipped
331 if path_from_env != path and warn_cmd_public:
332 warnings.add(u"Ansible is being run in a world writable directory (%s),"
333 u" ignoring it as an ansible.cfg source."
334 u" For more information see"
335 u" https://docs.ansible.com/ansible/devel/reference_appendices/config.html#cfg-in-world-writable-dir"
336 % to_text(cwd))
337
338 return path
339
340
341 def _add_base_defs_deprecations(base_defs):
342 """Add deprecation source 'ansible.builtin' to deprecations in base.yml"""
343 def process(entry):
344 if 'deprecated' in entry:
345 entry['deprecated']['collection_name'] = 'ansible.builtin'
346
347 for dummy, data in base_defs.items():
348 process(data)
349 for section in ('ini', 'env', 'vars'):
350 if section in data:
351 for entry in data[section]:
352 process(entry)
353
354
355 class ConfigManager:
356
357 DEPRECATED = [] # type: list[tuple[str, dict[str, str]]]
358 WARNINGS = set() # type: set[str]
359
360 _errors: list[tuple[str, Exception]]
361
362 def __init__(self, conf_file=None, defs_file=None):
363 self._get_ini_config_value = functools.cache(self._get_ini_config_value)
364
365 self._base_defs = {}
366 self._plugins = {}
367 self._parsers = {}
368
369 self._config_file = conf_file
370
371 self._base_defs = self._read_config_yaml_file(defs_file or ('%s/base.yml' % os.path.dirname(__file__)))
372 _add_base_defs_deprecations(self._base_defs)
373 _validate_secret_config_defs(self._base_defs)
374
375 if self._config_file is None:
376 # set config using ini
377 self._config_file = find_ini_config_file(self.WARNINGS)
378
379 # consume configuration
380 if self._config_file:
381 # initialize parser and read config
382 self._parse_config_file()
383
384 self._errors = []
385 """Deferred errors that will be turned into warnings."""
386
387 # ensure we always have config def entry
388 self._base_defs['CONFIG_FILE'] = {'default': None, 'type': 'path'}
389
390 def load_galaxy_server_defs(self, server_list):
391
392 def server_config_def(section, key, required, option_type):
393 config_def = {
394 'description': 'The %s of the %s Galaxy server' % (key, section),
395 'ini': [
396 {
397 'section': 'galaxy_server.%s' % section,
398 'key': key,
399 }
400 ],
401 'env': [
402 {'name': 'ANSIBLE_GALAXY_SERVER_%s_%s' % (section.upper(), key.upper())},
403 ],
404 'required': required,
405 'type': option_type,
406 }
407 if key in GALAXY_SERVER_ADDITIONAL:
408 config_def.update(GALAXY_SERVER_ADDITIONAL[key])
409 # ensure we always have a default timeout
410 if key == 'timeout' and 'default' not in config_def:
411 config_def['default'] = self.get_config_value('GALAXY_SERVER_TIMEOUT')
412
413 return config_def
414
415 if server_list:
416 for server_key in server_list:
417 if not server_key:
418 # To filter out empty strings or non truthy values as an empty server list env var is equal to [''].
419 continue
420
421 # Config definitions are looked up dynamically based on the C.GALAXY_SERVER_LIST entry. We look up the
422 # section [galaxy_server.<server>] for the values url, username, password, and token.
423 defs = dict((k, server_config_def(server_key, k, req, value_type)) for k, req, value_type in GALAXY_SERVER_DEF)
424 self.initialize_plugin_configuration_definitions('galaxy_server', server_key, defs)
425
426 def template_default(self, value, variables, key_name: str = '<unknown>'):
427 if isinstance(value, str) and (value.startswith('{{') and value.endswith('}}')) and variables is not None:
428 # template default values if possible
429 # NOTE: cannot use is_template due to circular dep
430 try:
431 # FIXME: This really should be using an immutable sandboxed native environment, not just native environment
432 template = NativeEnvironment().from_string(value)
433 value = template.render(variables)
434 except Exception as ex:
435 self._errors.append((f'Failed to template default for config {key_name}.', ex))
436 return value
437
438 def _read_config_yaml_file(self, yml_file):
439 # TODO: handle relative paths as relative to the directory containing the current playbook instead of CWD
440 # Currently this is only used with absolute paths to the `ansible/config` directory
441 yml_file = to_bytes(yml_file)
442 if os.path.exists(yml_file):
443 with open(yml_file, 'rb') as config_def:
444 return yaml_load(config_def) or {}
445 raise AnsibleError(
446 "Missing base YAML definition file (bad install?): %s" % to_native(yml_file))
447
448 def _parse_config_file(self, cfile=None):
449 """ return flat configuration settings from file(s) """
450 # TODO: take list of files with merge/nomerge
451
452 if cfile is None:
453 cfile = self._config_file
454
455 ftype = get_config_type(cfile)
456 if cfile is not None:
457 if ftype == 'ini':
458 self._parsers[cfile] = configparser.ConfigParser(inline_comment_prefixes=(';',))
459 with open(to_bytes(cfile), 'rb') as f:
460 try:
461 cfg_text = to_text(f.read(), errors='surrogate_or_strict')
462 except UnicodeError as e:
463 raise AnsibleOptionsError("Error reading config file(%s) because the config file was not utf8 encoded: %s" % (cfile, to_native(e)))
464 try:
465 self._parsers[cfile].read_string(cfg_text)
466 except configparser.Error as e:
467 raise AnsibleOptionsError("Error reading config file (%s): %s" % (cfile, to_native(e)))
468 # FIXME: this should eventually handle yaml config files
469 # elif ftype == 'yaml':
470 # with open(cfile, 'rb') as config_stream:
471 # self._parsers[cfile] = yaml_load(config_stream)
472 else:
473 raise AnsibleOptionsError("Unsupported configuration file type: %s" % to_native(ftype))
474
475 def _find_yaml_config_files(self):
476 """ Load YAML Config Files in order, check merge flags, keep origin of settings"""
477 pass
478
479 def get_plugin_options(self, plugin_type, name, keys=None, variables=None, direct=None):
480 options, dummy = self.get_plugin_options_and_origins(plugin_type, name, keys=keys, variables=variables, direct=direct)
481 return options
482
483 def get_plugin_options_and_origins(self, plugin_type, name, keys=None, variables=None, direct=None):
484 options = {}
485 origins = {}
486 defs = self.get_configuration_definitions(plugin_type=plugin_type, name=name)
487 for option in defs:
488 options[option], origins[option] = self.get_config_value_and_origin(option, plugin_type=plugin_type, plugin_name=name, keys=keys,
489 variables=variables, direct=direct)
490 return options, origins
491
492 def get_plugin_vars(self, plugin_type, name):
493
494 pvars = []
495 for pdef in self.get_configuration_definitions(plugin_type=plugin_type, name=name).values():
496 if 'vars' in pdef and pdef['vars']:
497 for var_entry in pdef['vars']:
498 pvars.append(var_entry['name'])
499 return pvars
500
501 def get_plugin_options_from_var(self, plugin_type, name, variable):
502
503 options = []
504 for option_name, pdef in self.get_configuration_definitions(plugin_type=plugin_type, name=name).items():
505 if 'vars' in pdef and pdef['vars']:
506 for var_entry in pdef['vars']:
507 if variable == var_entry['name']:
508 options.append(option_name)
509 return options
510
511 def get_configuration_definition(self, name, plugin_type=None, plugin_name=None):
512
513 ret = {}
514 if plugin_type is None:
515 ret = self._base_defs.get(name, None)
516 elif plugin_name is None:
517 ret = self._plugins.get(plugin_type, {}).get(name, None)
518 else:
519 ret = self._plugins.get(plugin_type, {}).get(plugin_name, {}).get(name, None)
520
521 return ret
522
523 def has_configuration_definition(self, plugin_type, name):
524
525 has = False
526 if plugin_type in self._plugins:
527 has = (name in self._plugins[plugin_type])
528
529 return has
530
531 def get_configuration_definitions(self, plugin_type=None, name=None, ignore_private=False):
532 """ just list the possible settings, either base or for specific plugins or plugin """
533
534 ret = {}
535 if plugin_type is None:
536 ret = self._base_defs
537 elif name is None:
538 ret = self._plugins.get(plugin_type, {})
539 else:
540 ret = self._plugins.get(plugin_type, {}).get(name, {})
541
542 if ignore_private: # ignore 'test' config entries, they should not change runtime behaviors
543 for cdef in list(ret.keys()):
544 if cdef.startswith('_Z_'):
545 del ret[cdef]
546 return ret
547
548 def _loop_entries(self, container, entry_list):
549 """ repeat code for value entry assignment """
550
551 value = None
552 origin = None
553 for entry in entry_list:
554 name = entry.get('name')
555 try:
556 temp_value = container.get(name, None)
557 except UnicodeEncodeError:
558 self.WARNINGS.add(u'value for config entry {0} contains invalid characters, ignoring...'.format(to_text(name)))
559 continue
560 if temp_value is not None: # only set if entry is defined in container
561 value = temp_value
562 origin = name
563
564 # deal with deprecation of setting source, if used
565 if 'deprecated' in entry:
566 self.DEPRECATED.append((entry['name'], entry['deprecated']))
567
568 return value, origin
569
570 def get_config_value(
571 self,
572 config: str,
573 cfile: str | None = None,
574 plugin_type: str | None = None,
575 plugin_name: str | None = None,
576 keys=None,
577 variables=None,
578 direct=None,
579 *,
580 templar: Templar | None = None,
581 ) -> t.Any:
582 """ wrapper """
583
584 try:
585 value, _drop = self.get_config_value_and_origin(config, cfile=cfile, plugin_type=plugin_type, plugin_name=plugin_name,
586 keys=keys, variables=variables, direct=direct, templar=templar)
587 except AnsibleError:
588 raise
589 except Exception as ex:
590 raise AnsibleError(f"Unhandled exception when retrieving {config!r}.") from ex
591 return value
592
593 def get_config_default(self, config: str, plugin_type: str | None = None, plugin_name: str | None = None) -> t.Any:
594 """Return the default value for the specified configuration."""
595 return self.get_configuration_definitions(plugin_type, plugin_name)[config]['default']
596
597 def get_config_value_and_origin(
598 self,
599 config: str,
600 cfile: str | None = None,
601 plugin_type: str | None = None,
602 plugin_name: str | None = None,
603 keys=None,
604 variables=None,
605 direct=None,
606 *,
607 templar: Templar | None = None
608 ) -> tuple[str, t.Any]:
609 """ Given a config key figure out the actual value and report on the origin of the settings """
610 if cfile is None:
611 # use default config
612 cfile = self._config_file
613
614 if config == 'CONFIG_FILE':
615 return cfile, ''
616
617 # Note: sources that are lists listed in low to high precedence (last one wins)
618 value = None
619 origin = None
620 origin_ftype = None
621
622 defs = self.get_configuration_definitions(plugin_type=plugin_type, name=plugin_name)
623 if config in defs:
624
625 aliases = defs[config].get('aliases', [])
626
627 # direct setting via plugin arguments, can set to None so we bypass rest of processing/defaults
628 if direct:
629 if config in direct:
630 value = direct[config]
631 origin = 'Direct'
632 else:
633 direct_aliases = [direct[alias] for alias in aliases if alias in direct]
634 if direct_aliases:
635 value = direct_aliases[0]
636 origin = 'Direct'
637
638 if value is None and variables and defs[config].get('vars'):
639 # Use 'variable overrides' if present, highest precedence, but only present when querying running play
640 value, origin = self._loop_entries(variables, defs[config]['vars'])
641 origin = 'var: %s' % origin
642
643 # use playbook keywords if you have em
644 if value is None and defs[config].get('keyword') and keys:
645 value, origin = self._loop_entries(keys, defs[config]['keyword'])
646 origin = 'keyword: %s' % origin
647
648 # automap to keywords
649 # TODO: deprecate these in favor of explicit keyword above
650 if value is None and keys:
651 if config in keys:
652 value = keys[config]
653 keyword = config
654
655 elif aliases:
656 for alias in aliases:
657 if alias in keys:
658 value = keys[alias]
659 keyword = alias
660 break
661
662 if value is not None:
663 origin = 'keyword: %s' % keyword
664
665 if value is None and 'cli' in defs[config]:
666 # avoid circular import .. until valid
667 from ansible import context
668 value, origin = self._loop_entries(context.CLIARGS, defs[config]['cli'])
669 origin = 'cli: %s' % origin
670
671 # env vars are next precedence
672 if value is None and defs[config].get('env'):
673 value, origin = self._loop_entries(os.environ, defs[config]['env'])
674 value = _tags.TrustedAsTemplate().tag(value)
675 origin = 'env: %s' % origin
676
677 # try config file entries next, if we have one
678 if self._parsers.get(cfile, None) is None:
679 self._parse_config_file(cfile)
680
681 # attempt to read from config file
682 if value is None and cfile is not None:
683 ftype = get_config_type(cfile)
684 if ftype and defs[config].get(ftype):
685 try:
686 for entry in defs[config][ftype]:
687 # load from config
688 if ftype == 'ini':
689 temp_value = self._get_ini_config_value(cfile, entry.get('section', 'defaults'), entry['key'])
690 elif ftype == 'yaml':
691 raise AnsibleError('YAML configuration type has not been implemented yet')
692 else:
693 raise AnsibleError('Invalid configuration file type: %s' % ftype)
694
695 if temp_value is not None:
696 # set value and origin
697 value = temp_value
698 origin = cfile
699 origin_ftype = ftype
700 if 'deprecated' in entry:
701 if ftype == 'ini':
702 self.DEPRECATED.append(('[%s]%s' % (entry['section'], entry['key']), entry['deprecated']))
703 else:
704 raise AnsibleError('Unimplemented file type: %s' % ftype)
705
706 except Exception as e:
707 sys.stderr.write("Error while loading config %s: %s" % (cfile, to_native(e)))
708
709 # set default if we got here w/o a value
710 if value is None:
711 if defs[config].get('required', False):
712 if not plugin_type or config not in INTERNAL_DEFS.get(plugin_type, {}):
713 raise AnsibleRequiredOptionError(f"Required config {_get_config_label(plugin_type, plugin_name, config)} not provided.")
714 else:
715 origin = 'default'
716 value = self.template_default(defs[config].get('default'), variables, key_name=_get_config_label(plugin_type, plugin_name, config))
717
718 if templar:
719 value = templar.template(value)
720
721 try:
722 # ensure correct type, can raise exceptions on mismatched types
723 value = ensure_type(value, defs[config].get('type'), origin=origin, origin_ftype=origin_ftype)
724 except ValueError as ex:
725 if origin.startswith('env:') and value == '':
726 # this is empty env var for non string so we can set to default
727 origin = 'default'
728 value = ensure_type(defs[config].get('default'), defs[config].get('type'), origin=origin, origin_ftype=origin_ftype)
729 else:
730 value_type = defs[config].get('type')
731 raise AnsibleOptionsError(
732 f'Config {_get_config_label(plugin_type, plugin_name, config)} from {origin!r} has an invalid value.',
733 help_text=f'Value must be of type {value_type!r}.',
734 ) from ex
735
736 # deal with restricted values
737 if value is not None and 'choices' in defs[config] and defs[config]['choices'] is not None:
738 invalid_choices = True # assume the worst!
739 if defs[config].get('type') == 'list':
740 # for a list type, compare all values in type are allowed
741 invalid_choices = not all(choice in defs[config]['choices'] for choice in value)
742 else:
743 # these should be only the simple data types (string, int, bool, float, etc) .. ignore dicts for now
744 invalid_choices = value not in defs[config]['choices']
745
746 if invalid_choices:
747
748 if isinstance(defs[config]['choices'], Mapping):
749 valid = ', '.join([to_text(k) for k in defs[config]['choices'].keys()])
750 elif isinstance(defs[config]['choices'], str):
751 valid = defs[config]['choices']
752 elif isinstance(defs[config]['choices'], Sequence):
753 valid = ', '.join([to_text(c) for c in defs[config]['choices']])
754 else:
755 valid = defs[config]['choices']
756
757 raise AnsibleOptionsError(
758 f'Config {_get_config_label(plugin_type, plugin_name, config)} from {origin!r} has an invalid value {value!r}.',
759 help_text=f'Valid values are: {valid}.',
760 )
761
762 # deal with deprecation of the setting
763 if 'deprecated' in defs[config] and origin != 'default':
764 self.DEPRECATED.append((config, defs[config].get('deprecated')))
765
766 # register the resolved value for masking if the config is marked secret
767 if value is not None and defs[config].get('secret'):
768 secrets: list[str] = []
769 secret_queue: list[object] = [value]
770 while secret_queue:
771 item = secret_queue.pop()
772 if isinstance(item, str):
773 secrets.append(item)
774 elif isinstance(item, (list, tuple)):
775 secret_queue.extend(item)
776
777 register_secrets(secrets)
778 else:
779 raise AnsibleUndefinedConfigEntry(f'No config definition exists for {_get_config_label(plugin_type, plugin_name, config)}.')
780
781 if not _tags.Origin.is_tagged_on(value):
782 value = _tags.Origin(description=f'<Config {origin}>').tag(value)
783
784 return value, origin
785
786 def initialize_plugin_configuration_definitions(self, plugin_type, name, defs):
787
788 _validate_secret_config_defs(defs, plugin_type=plugin_type, plugin_name=name)
789
790 if plugin_type not in self._plugins:
791 self._plugins[plugin_type] = {}
792
793 self._plugins[plugin_type][name] = defs
794
795 def _get_ini_config_value(self, config_file: str, section: str, option: str) -> t.Any:
796 """
797 Fetch `option` from the specified `section`.
798 Returns `None` if the specified `section` or `option` are not present.
799 Origin and TrustedAsTemplate tags are applied to returned values.
800
801 CAUTION: Although INI sourced configuration values are trusted for templating, that does not automatically mean they will be templated.
802 It is up to the code consuming configuration values to apply templating if required.
803 """
804 parser = self._parsers[config_file]
805 value = parser.get(section, option, raw=True, fallback=None)
806
807 if value is not None:
808 value = self._apply_tags(value, section, option)
809
810 return value
811
812 def _apply_tags(self, value: str, section: str, option: str) -> t.Any:
813 """Apply origin and trust to the given `value` sourced from the stated `section` and `option`."""
814 description = f'section {section!r} option {option!r}'
815 origin = _tags.Origin(path=self._config_file, description=description)
816 tags = [origin, _tags.TrustedAsTemplate()]
817 value = AnsibleTagHelper.tag(value, tags)
818
819 return value
820
821 @staticmethod
822 def get_deprecated_msg_from_config(dep_docs, include_removal=False, collection_name=None):
823
824 removal = ''
825 if include_removal:
826 if 'removed_at_date' in dep_docs:
827 removal = f"Will be removed in a release after {dep_docs['removed_at_date']}\n\t"
828 elif collection_name:
829 removal = f"Will be removed in: {collection_name} {dep_docs['removed_in']}\n\t"
830 else:
831 removal = f"Will be removed in: Ansible {dep_docs['removed_in']}\n\t"
832
833 # TODO: choose to deprecate either singular or plural
834 alt = dep_docs.get('alternatives', dep_docs.get('alternative', 'none'))
835 return f"Reason: {dep_docs['why']}\n\t{removal}Alternatives: {alt}"