| 1 |
# -*- coding: utf-8 -*- |
| 2 |
# Copyright (c) 2019 Ansible Project |
| 3 |
# Simplified BSD License (see licenses/simplified_bsd.txt or https://opensource.org/licenses/BSD-2-Clause) |
| 4 |
|
| 5 |
from __future__ import annotations |
| 6 |
|
| 7 |
import datetime |
| 8 |
import os |
| 9 |
import typing as t |
| 10 |
|
| 11 |
from collections import deque |
| 12 |
from collections.abc import ( |
| 13 |
KeysView, |
| 14 |
Set, |
| 15 |
Sequence, |
| 16 |
Mapping, |
| 17 |
MutableMapping, |
| 18 |
MutableSet, |
| 19 |
MutableSequence, |
| 20 |
) |
| 21 |
from itertools import chain # pylint: disable=unused-import |
| 22 |
|
| 23 |
from ansible.module_utils.common.collections import is_iterable |
| 24 |
from ansible.module_utils._internal import _no_six |
| 25 |
from ansible.module_utils._internal._datatag import AnsibleSerializable, AnsibleTagHelper |
| 26 |
from ansible.module_utils.common.text.converters import to_bytes, to_native, to_text |
| 27 |
from ansible.module_utils.common.warnings import warn |
| 28 |
from ansible.module_utils.datatag import native_type_name |
| 29 |
from ansible.module_utils.errors import ( |
| 30 |
AliasError, |
| 31 |
AnsibleFallbackNotFound, |
| 32 |
AnsibleValidationErrorMultiple, |
| 33 |
ArgumentTypeError, |
| 34 |
ArgumentValueError, |
| 35 |
ElementError, |
| 36 |
MutuallyExclusiveError, |
| 37 |
NoLogError, |
| 38 |
RequiredByError, |
| 39 |
RequiredError, |
| 40 |
RequiredIfError, |
| 41 |
RequiredOneOfError, |
| 42 |
RequiredTogetherError, |
| 43 |
SubParameterTypeError, |
| 44 |
) |
| 45 |
from ansible.module_utils.parsing.convert_bool import BOOLEANS_FALSE, BOOLEANS_TRUE |
| 46 |
from ansible.module_utils.common.validation import ( |
| 47 |
check_mutually_exclusive, |
| 48 |
check_required_arguments, |
| 49 |
check_required_together, |
| 50 |
check_required_one_of, |
| 51 |
check_required_if, |
| 52 |
check_required_by, |
| 53 |
check_type_bits, |
| 54 |
check_type_bool, |
| 55 |
check_type_bytes, |
| 56 |
check_type_dict, |
| 57 |
check_type_float, |
| 58 |
check_type_int, |
| 59 |
check_type_jsonarg, |
| 60 |
check_type_list, |
| 61 |
check_type_path, |
| 62 |
check_type_raw, |
| 63 |
check_type_str, |
| 64 |
) |
| 65 |
from ansible.module_utils.common.warnings import deprecate as _deprecate |
| 66 |
|
| 67 |
# Python2 & 3 way to get NoneType |
| 68 |
NoneType = type(None) |
| 69 |
|
| 70 |
_ADDITIONAL_CHECKS = ( |
| 71 |
{'func': check_required_together, 'attr': 'required_together', 'err': RequiredTogetherError}, |
| 72 |
{'func': check_required_one_of, 'attr': 'required_one_of', 'err': RequiredOneOfError}, |
| 73 |
{'func': check_required_if, 'attr': 'required_if', 'err': RequiredIfError}, |
| 74 |
{'func': check_required_by, 'attr': 'required_by', 'err': RequiredByError}, |
| 75 |
) |
| 76 |
|
| 77 |
# if adding boolean attribute, also add to PASS_BOOL |
| 78 |
# some of this dupes defaults from controller config |
| 79 |
# keep in sync with copy in lib/ansible/module_utils/csharp/Ansible.Basic.cs |
| 80 |
PASS_VARS: dict[str, t.Any] = { |
| 81 |
'check_mode': ('check_mode', False), |
| 82 |
'debug': ('_debug', False), |
| 83 |
'diff': ('_diff', False), |
| 84 |
'keep_remote_files': ('_keep_remote_files', False), |
| 85 |
'ignore_unknown_opts': ('_ignore_unknown_opts', False), |
| 86 |
'inject_invocation': ('_inject_invocation', False), |
| 87 |
'module_name': ('_name', None), |
| 88 |
'no_log': ('no_log', False), |
| 89 |
'remote_tmp': ('_remote_tmp', None), |
| 90 |
'target_log_info': ('_target_log_info', None), |
| 91 |
'selinux_special_fs': ('_selinux_special_fs', ['fuse', 'nfs', 'vboxsf', 'ramfs', '9p', 'vfat']), |
| 92 |
'shell_executable': ('_shell', '/bin/sh'), |
| 93 |
'socket': ('_socket_path', None), |
| 94 |
'syslog_facility': ('_syslog_facility', 'INFO'), |
| 95 |
'tmpdir': ('_tmpdir', None), |
| 96 |
'tracebacks_for': ('_tracebacks_for', frozenset()), |
| 97 |
'verbosity': ('_verbosity', 0), |
| 98 |
'version': ('ansible_version', '0.0'), |
| 99 |
} |
| 100 |
|
| 101 |
PASS_BOOLS = ('check_mode', 'debug', 'diff', 'keep_remote_files', 'ignore_unknown_opts', 'no_log') |
| 102 |
|
| 103 |
DEFAULT_TYPE_VALIDATORS = { |
| 104 |
'str': check_type_str, |
| 105 |
'list': check_type_list, |
| 106 |
'dict': check_type_dict, |
| 107 |
'bool': check_type_bool, |
| 108 |
'int': check_type_int, |
| 109 |
'float': check_type_float, |
| 110 |
'path': check_type_path, |
| 111 |
'raw': check_type_raw, |
| 112 |
'jsonarg': check_type_jsonarg, |
| 113 |
'json': check_type_jsonarg, |
| 114 |
'bytes': check_type_bytes, |
| 115 |
'bits': check_type_bits, |
| 116 |
} |
| 117 |
|
| 118 |
|
| 119 |
def _get_type_validator(wanted): |
| 120 |
"""Returns the callable used to validate a wanted type and the type name. |
| 121 |
|
| 122 |
:arg wanted: String or callable. If a string, get the corresponding |
| 123 |
validation function from DEFAULT_TYPE_VALIDATORS. If callable, |
| 124 |
get the name of the custom callable and return that for the type_checker. |
| 125 |
|
| 126 |
:returns: Tuple of callable function or None, and a string that is the name |
| 127 |
of the wanted type. |
| 128 |
""" |
| 129 |
|
| 130 |
# Use one of our builtin validators. |
| 131 |
if not callable(wanted): |
| 132 |
if wanted is None: |
| 133 |
# Default type for parameters |
| 134 |
wanted = 'str' |
| 135 |
|
| 136 |
type_checker = DEFAULT_TYPE_VALIDATORS.get(wanted) |
| 137 |
|
| 138 |
# Use the custom callable for validation. |
| 139 |
else: |
| 140 |
type_checker = wanted |
| 141 |
wanted = getattr(wanted, '__name__', to_native(type(wanted))) |
| 142 |
|
| 143 |
return type_checker, wanted |
| 144 |
|
| 145 |
|
| 146 |
def _get_legal_inputs(argument_spec, parameters, aliases=None): |
| 147 |
if aliases is None: |
| 148 |
aliases = _handle_aliases(argument_spec, parameters) |
| 149 |
|
| 150 |
return list(aliases.keys()) + list(argument_spec.keys()) |
| 151 |
|
| 152 |
|
| 153 |
def _get_unsupported_parameters(argument_spec, parameters, legal_inputs=None, options_context=None, store_supported=None): |
| 154 |
"""Check keys in parameters against those provided in legal_inputs |
| 155 |
to ensure they contain legal values. If legal_inputs are not supplied, |
| 156 |
they will be generated using the argument_spec. |
| 157 |
|
| 158 |
:arg argument_spec: Dictionary of parameters, their type, and valid values. |
| 159 |
:arg parameters: Dictionary of parameters. |
| 160 |
:arg legal_inputs: List of valid key names property names. Overrides values |
| 161 |
in argument_spec. |
| 162 |
:arg options_context: List of parent keys for tracking the context of where |
| 163 |
a parameter is defined. |
| 164 |
|
| 165 |
:returns: Set of unsupported parameters. Empty set if no unsupported parameters |
| 166 |
are found. |
| 167 |
""" |
| 168 |
|
| 169 |
if legal_inputs is None: |
| 170 |
legal_inputs = _get_legal_inputs(argument_spec, parameters) |
| 171 |
|
| 172 |
unsupported_parameters = set() |
| 173 |
for k in parameters.keys(): |
| 174 |
if k not in legal_inputs: |
| 175 |
context = k |
| 176 |
if options_context: |
| 177 |
context = tuple(options_context + [k]) |
| 178 |
|
| 179 |
unsupported_parameters.add(context) |
| 180 |
|
| 181 |
if store_supported is not None: |
| 182 |
supported_aliases = _handle_aliases(argument_spec, parameters) |
| 183 |
supported_params = [] |
| 184 |
for option in legal_inputs: |
| 185 |
if option in supported_aliases: |
| 186 |
continue |
| 187 |
supported_params.append(option) |
| 188 |
|
| 189 |
store_supported.update({context: (supported_params, supported_aliases)}) |
| 190 |
|
| 191 |
return unsupported_parameters |
| 192 |
|
| 193 |
|
| 194 |
def _handle_aliases(argument_spec, parameters, alias_warnings=None, alias_deprecations=None): |
| 195 |
"""Process aliases from an argument_spec including warnings and deprecations. |
| 196 |
|
| 197 |
Modify ``parameters`` by adding a new key for each alias with the supplied |
| 198 |
value from ``parameters``. |
| 199 |
|
| 200 |
If a list is provided to the alias_warnings parameter, it will be filled with tuples |
| 201 |
(option, alias) in every case where both an option and its alias are specified. |
| 202 |
|
| 203 |
If a list is provided to alias_deprecations, it will be populated with dictionaries, |
| 204 |
each containing deprecation information for each alias found in argument_spec. |
| 205 |
|
| 206 |
:param argument_spec: Dictionary of parameters, their type, and valid values. |
| 207 |
:type argument_spec: dict |
| 208 |
|
| 209 |
:param parameters: Dictionary of parameters. |
| 210 |
:type parameters: dict |
| 211 |
|
| 212 |
:param alias_warnings: |
| 213 |
:type alias_warnings: list |
| 214 |
|
| 215 |
:param alias_deprecations: |
| 216 |
:type alias_deprecations: list |
| 217 |
""" |
| 218 |
|
| 219 |
aliases_results = {} # alias:canon |
| 220 |
|
| 221 |
for (k, v) in argument_spec.items(): |
| 222 |
aliases = v.get('aliases', None) |
| 223 |
default = v.get('default', None) |
| 224 |
required = v.get('required', False) |
| 225 |
|
| 226 |
if alias_deprecations is not None: |
| 227 |
for alias in argument_spec[k].get('deprecated_aliases', []): |
| 228 |
if alias.get('name') in parameters: |
| 229 |
alias_deprecations.append(alias) |
| 230 |
|
| 231 |
if default is not None and required: |
| 232 |
# not alias specific but this is a good place to check this |
| 233 |
raise ValueError("internal error: required and default are mutually exclusive for %s" % k) |
| 234 |
|
| 235 |
if aliases is None: |
| 236 |
continue |
| 237 |
|
| 238 |
if not is_iterable(aliases) or isinstance(aliases, (bytes, str)): |
| 239 |
raise TypeError('internal error: aliases must be a list or tuple') |
| 240 |
|
| 241 |
for alias in aliases: |
| 242 |
aliases_results[alias] = k |
| 243 |
if alias in parameters: |
| 244 |
if k in parameters and alias_warnings is not None: |
| 245 |
alias_warnings.append((k, alias)) |
| 246 |
parameters[k] = parameters[alias] |
| 247 |
|
| 248 |
return aliases_results |
| 249 |
|
| 250 |
|
| 251 |
def _list_deprecations(argument_spec, parameters, prefix=''): |
| 252 |
"""Return a list of deprecations |
| 253 |
|
| 254 |
:arg argument_spec: An argument spec dictionary |
| 255 |
:arg parameters: Dictionary of parameters |
| 256 |
|
| 257 |
:returns: List of dictionaries containing a message and version in which |
| 258 |
the deprecated parameter will be removed, or an empty list. |
| 259 |
|
| 260 |
:Example return: |
| 261 |
|
| 262 |
.. code-block:: python |
| 263 |
|
| 264 |
[ |
| 265 |
{ |
| 266 |
'msg': "Param 'deptest' is deprecated. See the module docs for more information", |
| 267 |
'version': '2.9' |
| 268 |
} |
| 269 |
] |
| 270 |
""" |
| 271 |
|
| 272 |
deprecations = [] |
| 273 |
for arg_name, arg_opts in argument_spec.items(): |
| 274 |
if arg_name in parameters: |
| 275 |
if prefix: |
| 276 |
sub_prefix = '%s["%s"]' % (prefix, arg_name) |
| 277 |
else: |
| 278 |
sub_prefix = arg_name |
| 279 |
if arg_opts.get('removed_at_date') is not None: |
| 280 |
deprecations.append({ |
| 281 |
'msg': "Param '%s' is deprecated. See the module docs for more information" % sub_prefix, |
| 282 |
'date': arg_opts.get('removed_at_date'), |
| 283 |
'collection_name': arg_opts.get('removed_from_collection'), |
| 284 |
}) |
| 285 |
elif arg_opts.get('removed_in_version') is not None: |
| 286 |
deprecations.append({ |
| 287 |
'msg': "Param '%s' is deprecated. See the module docs for more information" % sub_prefix, |
| 288 |
'version': arg_opts.get('removed_in_version'), |
| 289 |
'collection_name': arg_opts.get('removed_from_collection'), |
| 290 |
}) |
| 291 |
# Check sub-argument spec |
| 292 |
sub_argument_spec = arg_opts.get('options') |
| 293 |
if sub_argument_spec is not None: |
| 294 |
sub_arguments = parameters[arg_name] |
| 295 |
if isinstance(sub_arguments, Mapping): |
| 296 |
sub_arguments = [sub_arguments] |
| 297 |
if isinstance(sub_arguments, list): |
| 298 |
for sub_params in sub_arguments: |
| 299 |
if isinstance(sub_params, Mapping): |
| 300 |
deprecations.extend(_list_deprecations(sub_argument_spec, sub_params, prefix=sub_prefix)) |
| 301 |
|
| 302 |
return deprecations |
| 303 |
|
| 304 |
|
| 305 |
def _list_no_log_values(argument_spec, params): |
| 306 |
"""Return set of no log values |
| 307 |
|
| 308 |
:arg argument_spec: An argument spec dictionary |
| 309 |
:arg params: Dictionary of all parameters |
| 310 |
|
| 311 |
:returns: :class:`set` of strings that should be hidden from output: |
| 312 |
""" |
| 313 |
|
| 314 |
no_log_values = set() |
| 315 |
for arg_name, arg_opts in argument_spec.items(): |
| 316 |
if arg_opts.get('no_log', False): |
| 317 |
# Find the value for the no_log'd param |
| 318 |
no_log_object = params.get(arg_name, None) |
| 319 |
|
| 320 |
if no_log_object: |
| 321 |
try: |
| 322 |
no_log_values.update(_return_datastructure_name(no_log_object)) |
| 323 |
except TypeError as e: |
| 324 |
raise TypeError('Failed to convert "%s": %s' % (arg_name, to_native(e))) |
| 325 |
|
| 326 |
# Get no_log values from suboptions |
| 327 |
sub_argument_spec = arg_opts.get('options') |
| 328 |
if sub_argument_spec is not None: |
| 329 |
wanted_type = arg_opts.get('type') |
| 330 |
sub_parameters = params.get(arg_name) |
| 331 |
|
| 332 |
if sub_parameters is not None: |
| 333 |
if wanted_type == 'dict' or (wanted_type == 'list' and arg_opts.get('elements', '') == 'dict'): |
| 334 |
# Sub parameters can be a dict or list of dicts. Ensure parameters are always a list. |
| 335 |
if not isinstance(sub_parameters, list): |
| 336 |
sub_parameters = [sub_parameters] |
| 337 |
|
| 338 |
for sub_param in sub_parameters: |
| 339 |
# Validate dict fields in case they came in as strings |
| 340 |
|
| 341 |
if isinstance(sub_param, str): |
| 342 |
sub_param = check_type_dict(sub_param) |
| 343 |
|
| 344 |
if not isinstance(sub_param, Mapping): |
| 345 |
raise TypeError("Value '{1}' in the sub parameter field '{0}' must be a {2}, " |
| 346 |
"not '{1.__class__.__name__}'".format(arg_name, sub_param, wanted_type)) |
| 347 |
|
| 348 |
no_log_values.update(_list_no_log_values(sub_argument_spec, sub_param)) |
| 349 |
|
| 350 |
return no_log_values |
| 351 |
|
| 352 |
|
| 353 |
def _return_datastructure_name(obj): |
| 354 |
""" Return native stringified values from datastructures. |
| 355 |
|
| 356 |
For use with removing sensitive values pre-jsonification.""" |
| 357 |
if isinstance(obj, (str, bytes)): |
| 358 |
if obj: |
| 359 |
yield to_native(obj, errors='surrogate_or_strict') |
| 360 |
return |
| 361 |
elif isinstance(obj, Mapping): |
| 362 |
for element in obj.items(): |
| 363 |
yield from _return_datastructure_name(element[1]) |
| 364 |
elif is_iterable(obj): |
| 365 |
for element in obj: |
| 366 |
yield from _return_datastructure_name(element) |
| 367 |
elif obj is None or isinstance(obj, bool): |
| 368 |
# This must come before int because bools are also ints |
| 369 |
return |
| 370 |
elif isinstance(obj, (int, float)): |
| 371 |
yield to_native(obj, nonstring='simplerepr') |
| 372 |
else: |
| 373 |
raise TypeError('Unknown parameter type: %s' % (type(obj))) |
| 374 |
|
| 375 |
|
| 376 |
def _remove_values_conditions(value, no_log_strings, deferred_removals): |
| 377 |
""" |
| 378 |
Helper function for :meth:`remove_values`. |
| 379 |
|
| 380 |
:arg value: The value to check for strings that need to be stripped |
| 381 |
:arg no_log_strings: set of strings which must be stripped out of any values |
| 382 |
:arg deferred_removals: List which holds information about nested |
| 383 |
containers that have to be iterated for removals. It is passed into |
| 384 |
this function so that more entries can be added to it if value is |
| 385 |
a container type. The format of each entry is a 2-tuple where the first |
| 386 |
element is the ``value`` parameter and the second value is a new |
| 387 |
container to copy the elements of ``value`` into once iterated. |
| 388 |
|
| 389 |
:returns: if ``value`` is a scalar, returns ``value`` with two exceptions: |
| 390 |
|
| 391 |
1. :class:`~datetime.datetime` objects which are changed into a string representation. |
| 392 |
2. objects which are in ``no_log_strings`` are replaced with a placeholder |
| 393 |
so that no sensitive data is leaked. |
| 394 |
|
| 395 |
If ``value`` is a container type, returns a new empty container. |
| 396 |
|
| 397 |
``deferred_removals`` is added to as a side-effect of this function. |
| 398 |
|
| 399 |
.. warning:: It is up to the caller to make sure the order in which value |
| 400 |
is passed in is correct. For instance, higher level containers need |
| 401 |
to be passed in before lower level containers. For example, given |
| 402 |
``{'level1': {'level2': 'level3': [True]} }`` first pass in the |
| 403 |
dictionary for ``level1``, then the dict for ``level2``, and finally |
| 404 |
the list for ``level3``. |
| 405 |
""" |
| 406 |
original_value = value |
| 407 |
|
| 408 |
if isinstance(value, (str, bytes)): |
| 409 |
# Need native str type |
| 410 |
native_str_value = value |
| 411 |
if isinstance(value, str): |
| 412 |
value_is_text = True |
| 413 |
elif isinstance(value, bytes): |
| 414 |
value_is_text = False |
| 415 |
native_str_value = to_text(value, errors='surrogate_or_strict') |
| 416 |
|
| 417 |
if native_str_value in no_log_strings: |
| 418 |
return 'VALUE_SPECIFIED_IN_NO_LOG_PARAMETER' |
| 419 |
for omit_me in no_log_strings: |
| 420 |
native_str_value = native_str_value.replace(omit_me, '*' * 8) |
| 421 |
|
| 422 |
if value_is_text and isinstance(native_str_value, bytes): |
| 423 |
value = to_text(native_str_value, encoding='utf-8', errors='surrogate_then_replace') |
| 424 |
elif not value_is_text and isinstance(native_str_value, str): |
| 425 |
value = to_bytes(native_str_value, encoding='utf-8', errors='surrogate_then_replace') |
| 426 |
else: |
| 427 |
value = native_str_value |
| 428 |
|
| 429 |
elif value is True or value is False or value is None: |
| 430 |
return value |
| 431 |
|
| 432 |
elif isinstance(value, Sequence): |
| 433 |
new_value = AnsibleTagHelper.tag_copy(original_value, []) |
| 434 |
deferred_removals.append((value, new_value)) |
| 435 |
return new_value |
| 436 |
|
| 437 |
elif isinstance(value, Set): |
| 438 |
new_value = AnsibleTagHelper.tag_copy(original_value, set()) |
| 439 |
deferred_removals.append((value, new_value)) |
| 440 |
return new_value |
| 441 |
|
| 442 |
elif isinstance(value, Mapping): |
| 443 |
new_value = AnsibleTagHelper.tag_copy(original_value, {}) |
| 444 |
deferred_removals.append((value, new_value)) |
| 445 |
return new_value |
| 446 |
|
| 447 |
elif isinstance(value, (int, float)): |
| 448 |
stringy_value = to_native(value, encoding='utf-8', errors='surrogate_or_strict') |
| 449 |
if stringy_value in no_log_strings: |
| 450 |
return 'VALUE_SPECIFIED_IN_NO_LOG_PARAMETER' |
| 451 |
for omit_me in no_log_strings: |
| 452 |
if omit_me in stringy_value: |
| 453 |
return 'VALUE_SPECIFIED_IN_NO_LOG_PARAMETER' |
| 454 |
|
| 455 |
elif isinstance(value, (datetime.datetime, datetime.date, datetime.time)): |
| 456 |
return value |
| 457 |
elif isinstance(value, AnsibleSerializable): |
| 458 |
return value |
| 459 |
else: |
| 460 |
raise TypeError('Value of unknown type: %s, %s' % (type(value), value)) |
| 461 |
|
| 462 |
value = AnsibleTagHelper.tag_copy(original_value, value) |
| 463 |
|
| 464 |
return value |
| 465 |
|
| 466 |
|
| 467 |
def _set_defaults(argument_spec, parameters, set_default=True): |
| 468 |
"""Set default values for parameters when no value is supplied. |
| 469 |
|
| 470 |
Modifies parameters directly. |
| 471 |
|
| 472 |
:arg argument_spec: Argument spec |
| 473 |
:type argument_spec: dict |
| 474 |
|
| 475 |
:arg parameters: Parameters to evaluate |
| 476 |
:type parameters: dict |
| 477 |
|
| 478 |
:kwarg set_default: Whether or not to set the default values |
| 479 |
:type set_default: bool |
| 480 |
|
| 481 |
:returns: Set of strings that should not be logged. |
| 482 |
:rtype: set |
| 483 |
""" |
| 484 |
|
| 485 |
no_log_values = set() |
| 486 |
for param, value in argument_spec.items(): |
| 487 |
|
| 488 |
# TODO: Change the default value from None to Sentinel to differentiate between |
| 489 |
# user supplied None and a default value set by this function. |
| 490 |
default = value.get('default', None) |
| 491 |
|
| 492 |
# This prevents setting defaults on required items on the 1st run, |
| 493 |
# otherwise will set things without a default to None on the 2nd. |
| 494 |
if param not in parameters and (default is not None or set_default): |
| 495 |
# Make sure any default value for no_log fields are masked. |
| 496 |
if value.get('no_log', False) and default: |
| 497 |
no_log_values.add(default) |
| 498 |
|
| 499 |
parameters[param] = default |
| 500 |
|
| 501 |
return no_log_values |
| 502 |
|
| 503 |
|
| 504 |
def _sanitize_keys_conditions(value, deferred_removals): |
| 505 |
""" Helper method to :func:`sanitize_keys` to build ``deferred_removals`` and avoid deep recursion. """ |
| 506 |
if isinstance(value, (str, bytes)): |
| 507 |
return value |
| 508 |
|
| 509 |
if isinstance(value, Sequence): |
| 510 |
if isinstance(value, MutableSequence): |
| 511 |
new_value = type(value)() |
| 512 |
else: |
| 513 |
new_value = [] # Need a mutable value |
| 514 |
deferred_removals.append((value, new_value)) |
| 515 |
return new_value |
| 516 |
|
| 517 |
if isinstance(value, Set): |
| 518 |
if isinstance(value, MutableSet): |
| 519 |
new_value = type(value)() |
| 520 |
else: |
| 521 |
new_value = set() # Need a mutable value |
| 522 |
deferred_removals.append((value, new_value)) |
| 523 |
return new_value |
| 524 |
|
| 525 |
if isinstance(value, Mapping): |
| 526 |
if isinstance(value, MutableMapping): |
| 527 |
new_value = type(value)() |
| 528 |
else: |
| 529 |
new_value = {} # Need a mutable value |
| 530 |
deferred_removals.append((value, new_value)) |
| 531 |
return new_value |
| 532 |
|
| 533 |
if isinstance(value, (int, float, bool, NoneType)): |
| 534 |
return value |
| 535 |
|
| 536 |
if isinstance(value, (datetime.datetime, datetime.date, datetime.time)): |
| 537 |
return value |
| 538 |
|
| 539 |
raise TypeError('Value of unknown type: %s, %s' % (type(value), value)) |
| 540 |
|
| 541 |
|
| 542 |
def _validate_elements(wanted_type, parameter, values, options_context=None, errors=None): |
| 543 |
|
| 544 |
if errors is None: |
| 545 |
errors = AnsibleValidationErrorMultiple() |
| 546 |
|
| 547 |
type_checker, wanted_element_type = _get_type_validator(wanted_type) |
| 548 |
validated_parameters = [] |
| 549 |
# Get param name for strings so we can later display this value in a useful error message if needed |
| 550 |
# Only pass 'kwargs' to our checkers and ignore custom callable checkers |
| 551 |
kwargs = {} |
| 552 |
if wanted_element_type == 'str' and isinstance(wanted_type, str): |
| 553 |
if isinstance(parameter, str): |
| 554 |
kwargs['param'] = parameter |
| 555 |
elif isinstance(parameter, dict): |
| 556 |
kwargs['param'] = list(parameter.keys())[0] |
| 557 |
|
| 558 |
for value in values: |
| 559 |
try: |
| 560 |
validated_parameters.append(type_checker(value, **kwargs)) |
| 561 |
except (TypeError, ValueError) as e: |
| 562 |
msg = "Elements value for option '%s'" % parameter |
| 563 |
if options_context: |
| 564 |
msg += " found in '%s'" % " -> ".join(options_context) |
| 565 |
msg += " is of type %s and we were unable to convert to %s: %s" % (native_type_name(value), wanted_element_type, to_native(e)) |
| 566 |
errors.append(ElementError(msg)) |
| 567 |
return validated_parameters |
| 568 |
|
| 569 |
|
| 570 |
def _validate_argument_types(argument_spec, parameters, prefix='', options_context=None, errors=None): |
| 571 |
"""Validate that parameter types match the type in the argument spec. |
| 572 |
|
| 573 |
Determine the appropriate type checker function and run each |
| 574 |
parameter value through that function. All error messages from type checker |
| 575 |
functions are returned. If any parameter fails to validate, it will not |
| 576 |
be in the returned parameters. |
| 577 |
|
| 578 |
:arg argument_spec: Argument spec |
| 579 |
:type argument_spec: dict |
| 580 |
|
| 581 |
:arg parameters: Parameters |
| 582 |
:type parameters: dict |
| 583 |
|
| 584 |
:kwarg prefix: Name of the parent key that contains the spec. Used in the error message |
| 585 |
:type prefix: str |
| 586 |
|
| 587 |
:kwarg options_context: List of contexts? |
| 588 |
:type options_context: list |
| 589 |
|
| 590 |
:returns: Two item tuple containing validated and coerced parameters |
| 591 |
and a list of any errors that were encountered. |
| 592 |
:rtype: tuple |
| 593 |
|
| 594 |
""" |
| 595 |
|
| 596 |
if errors is None: |
| 597 |
errors = AnsibleValidationErrorMultiple() |
| 598 |
|
| 599 |
for param, spec in argument_spec.items(): |
| 600 |
if param not in parameters: |
| 601 |
continue |
| 602 |
|
| 603 |
value = parameters[param] |
| 604 |
if value is None and not spec.get('required') and spec.get('default') is None: |
| 605 |
continue |
| 606 |
|
| 607 |
wanted_type = spec.get('type') |
| 608 |
type_checker, wanted_name = _get_type_validator(wanted_type) |
| 609 |
# Get param name for strings so we can later display this value in a useful error message if needed |
| 610 |
# Only pass 'kwargs' to our checkers and ignore custom callable checkers |
| 611 |
kwargs = {} |
| 612 |
if wanted_name == 'str' and isinstance(wanted_type, str): |
| 613 |
kwargs['param'] = list(parameters.keys())[0] |
| 614 |
|
| 615 |
# Get the name of the parent key if this is a nested option |
| 616 |
if prefix: |
| 617 |
kwargs['prefix'] = prefix |
| 618 |
|
| 619 |
try: |
| 620 |
parameters[param] = type_checker(value, **kwargs) |
| 621 |
elements_wanted_type = spec.get('elements', None) |
| 622 |
if elements_wanted_type: |
| 623 |
elements = parameters[param] |
| 624 |
if not isinstance(parameters[param], list) or not isinstance(elements, list): |
| 625 |
msg = "Invalid type %s for option '%s'" % (wanted_name, elements) |
| 626 |
if options_context: |
| 627 |
msg += " found in '%s'." % " -> ".join(options_context) |
| 628 |
msg += ", elements value check is supported only with 'list' type" |
| 629 |
errors.append(ArgumentTypeError(msg)) |
| 630 |
parameters[param] = _validate_elements(elements_wanted_type, param, elements, options_context, errors) |
| 631 |
|
| 632 |
except (TypeError, ValueError) as e: |
| 633 |
msg = "argument '%s' is of type %s" % (param, native_type_name(value)) |
| 634 |
if options_context: |
| 635 |
msg += " found in '%s'." % " -> ".join(options_context) |
| 636 |
msg += " and we were unable to convert to %s: %s" % (wanted_name, to_native(e)) |
| 637 |
errors.append(ArgumentTypeError(msg)) |
| 638 |
|
| 639 |
|
| 640 |
def _validate_argument_values(argument_spec, parameters, options_context=None, errors=None): |
| 641 |
"""Ensure all arguments have the requested values, and there are no stray arguments""" |
| 642 |
|
| 643 |
if errors is None: |
| 644 |
errors = AnsibleValidationErrorMultiple() |
| 645 |
|
| 646 |
for param, spec in argument_spec.items(): |
| 647 |
choices = spec.get('choices') |
| 648 |
if choices is None: |
| 649 |
continue |
| 650 |
|
| 651 |
if isinstance(choices, (frozenset, KeysView, Sequence)) and not isinstance(choices, (bytes, str)): |
| 652 |
if param in parameters: |
| 653 |
# Allow one or more when type='list' param with choices |
| 654 |
if isinstance(parameters[param], list): |
| 655 |
diff_list = [item for item in parameters[param] if item not in choices] |
| 656 |
if diff_list: |
| 657 |
choices_str = ", ".join([to_native(c) for c in choices]) |
| 658 |
diff_str = ", ".join([to_native(c) for c in diff_list]) |
| 659 |
msg = "value of %s must be one or more of: %s. Got no match for: %s" % (param, choices_str, diff_str) |
| 660 |
if options_context: |
| 661 |
msg = "{0} found in {1}".format(msg, " -> ".join(options_context)) |
| 662 |
errors.append(ArgumentValueError(msg)) |
| 663 |
elif parameters[param] not in choices: |
| 664 |
# PyYaml converts certain strings to bools. If we can unambiguously convert back, do so before checking |
| 665 |
# the value. If we can't figure this out, module author is responsible. |
| 666 |
if parameters[param] == 'False': |
| 667 |
overlap = BOOLEANS_FALSE.intersection(choices) |
| 668 |
if len(overlap) == 1: |
| 669 |
# Extract from a set |
| 670 |
(parameters[param],) = overlap |
| 671 |
|
| 672 |
if parameters[param] == 'True': |
| 673 |
overlap = BOOLEANS_TRUE.intersection(choices) |
| 674 |
if len(overlap) == 1: |
| 675 |
(parameters[param],) = overlap |
| 676 |
|
| 677 |
if parameters[param] not in choices: |
| 678 |
choices_str = ", ".join([to_native(c) for c in choices]) |
| 679 |
msg = "value of %s must be one of: %s, got: %s" % (param, choices_str, parameters[param]) |
| 680 |
if options_context: |
| 681 |
msg = "{0} found in {1}".format(msg, " -> ".join(options_context)) |
| 682 |
errors.append(ArgumentValueError(msg)) |
| 683 |
else: |
| 684 |
msg = "internal error: choices for argument %s are not iterable: %s" % (param, choices) |
| 685 |
if options_context: |
| 686 |
msg = "{0} found in {1}".format(msg, " -> ".join(options_context)) |
| 687 |
errors.append(ArgumentTypeError(msg)) |
| 688 |
|
| 689 |
|
| 690 |
def _validate_sub_spec( |
| 691 |
argument_spec, |
| 692 |
parameters, |
| 693 |
prefix="", |
| 694 |
options_context=None, |
| 695 |
errors=None, |
| 696 |
no_log_values=None, |
| 697 |
unsupported_parameters=None, |
| 698 |
supported_parameters=None, |
| 699 |
alias_deprecations=None, |
| 700 |
): |
| 701 |
"""Validate sub argument spec. |
| 702 |
|
| 703 |
This function is recursive. |
| 704 |
""" |
| 705 |
|
| 706 |
if options_context is None: |
| 707 |
options_context = [] |
| 708 |
|
| 709 |
if errors is None: |
| 710 |
errors = AnsibleValidationErrorMultiple() |
| 711 |
|
| 712 |
if no_log_values is None: |
| 713 |
no_log_values = set() |
| 714 |
|
| 715 |
if unsupported_parameters is None: |
| 716 |
unsupported_parameters = set() |
| 717 |
if supported_parameters is None: |
| 718 |
supported_parameters = dict() |
| 719 |
|
| 720 |
for param, value in argument_spec.items(): |
| 721 |
wanted = value.get('type') |
| 722 |
if wanted == 'dict' or (wanted == 'list' and value.get('elements', '') == 'dict'): |
| 723 |
sub_spec = value.get('options') |
| 724 |
if value.get('apply_defaults', False): |
| 725 |
if sub_spec is not None: |
| 726 |
if parameters.get(param) is None: |
| 727 |
parameters[param] = {} |
| 728 |
else: |
| 729 |
continue |
| 730 |
elif sub_spec is None or param not in parameters or parameters[param] is None: |
| 731 |
continue |
| 732 |
|
| 733 |
# Keep track of context for warning messages |
| 734 |
options_context.append(param) |
| 735 |
|
| 736 |
# Make sure we can iterate over the elements |
| 737 |
if not isinstance(parameters[param], Sequence) or isinstance(parameters[param], str): |
| 738 |
elements = [parameters[param]] |
| 739 |
else: |
| 740 |
elements = parameters[param] |
| 741 |
|
| 742 |
for idx, sub_parameters in enumerate(elements): |
| 743 |
no_log_values.update(set_fallbacks(sub_spec, sub_parameters)) |
| 744 |
|
| 745 |
if not isinstance(sub_parameters, dict): |
| 746 |
errors.append(SubParameterTypeError("value of '%s' must be of type dict or list of dicts" % param)) |
| 747 |
continue |
| 748 |
|
| 749 |
# Set prefix for warning messages |
| 750 |
new_prefix = prefix + param |
| 751 |
if wanted == 'list': |
| 752 |
new_prefix += '[%d]' % idx |
| 753 |
new_prefix += '.' |
| 754 |
|
| 755 |
alias_warnings = [] |
| 756 |
alias_deprecations_sub = [] |
| 757 |
try: |
| 758 |
options_aliases = _handle_aliases(sub_spec, sub_parameters, alias_warnings, alias_deprecations_sub) |
| 759 |
except (TypeError, ValueError) as e: |
| 760 |
options_aliases = {} |
| 761 |
errors.append(AliasError(to_native(e))) |
| 762 |
|
| 763 |
for option, alias in alias_warnings: |
| 764 |
warn('Both option %s%s and its alias %s%s are set.' % (new_prefix, option, new_prefix, alias)) |
| 765 |
|
| 766 |
if alias_deprecations is not None: |
| 767 |
for deprecation in alias_deprecations_sub: |
| 768 |
alias_deprecations.append({ |
| 769 |
'name': '%s%s' % (new_prefix, deprecation['name']), |
| 770 |
'version': deprecation.get('version'), |
| 771 |
'date': deprecation.get('date'), |
| 772 |
'collection_name': deprecation.get('collection_name'), |
| 773 |
}) |
| 774 |
|
| 775 |
try: |
| 776 |
no_log_values.update(_list_no_log_values(sub_spec, sub_parameters)) |
| 777 |
except TypeError as te: |
| 778 |
errors.append(NoLogError(to_native(te))) |
| 779 |
|
| 780 |
legal_inputs = _get_legal_inputs(sub_spec, sub_parameters, options_aliases) |
| 781 |
unsupported_parameters.update( |
| 782 |
_get_unsupported_parameters( |
| 783 |
sub_spec, |
| 784 |
sub_parameters, |
| 785 |
legal_inputs, |
| 786 |
options_context, |
| 787 |
store_supported=supported_parameters, |
| 788 |
) |
| 789 |
) |
| 790 |
|
| 791 |
try: |
| 792 |
check_mutually_exclusive(value.get('mutually_exclusive'), sub_parameters, options_context) |
| 793 |
except TypeError as e: |
| 794 |
errors.append(MutuallyExclusiveError(to_native(e))) |
| 795 |
|
| 796 |
no_log_values.update(_set_defaults(sub_spec, sub_parameters, False)) |
| 797 |
|
| 798 |
try: |
| 799 |
check_required_arguments(sub_spec, sub_parameters, options_context) |
| 800 |
except TypeError as e: |
| 801 |
errors.append(RequiredError(to_native(e))) |
| 802 |
|
| 803 |
_validate_argument_types(sub_spec, sub_parameters, new_prefix, options_context, errors=errors) |
| 804 |
_validate_argument_values(sub_spec, sub_parameters, options_context, errors=errors) |
| 805 |
|
| 806 |
for check in _ADDITIONAL_CHECKS: |
| 807 |
try: |
| 808 |
check['func'](value.get(check['attr']), sub_parameters, options_context) |
| 809 |
except TypeError as e: |
| 810 |
errors.append(check['err'](to_native(e))) |
| 811 |
|
| 812 |
no_log_values.update(_set_defaults(sub_spec, sub_parameters)) |
| 813 |
|
| 814 |
# Handle nested specs |
| 815 |
_validate_sub_spec( |
| 816 |
sub_spec, sub_parameters, new_prefix, options_context, errors, no_log_values, |
| 817 |
unsupported_parameters, supported_parameters, alias_deprecations) |
| 818 |
|
| 819 |
options_context.pop() |
| 820 |
|
| 821 |
|
| 822 |
def env_fallback(*args, **kwargs): |
| 823 |
"""Load value from environment variable""" |
| 824 |
|
| 825 |
for arg in args: |
| 826 |
if arg in os.environ: |
| 827 |
return os.environ[arg] |
| 828 |
raise AnsibleFallbackNotFound |
| 829 |
|
| 830 |
|
| 831 |
def set_fallbacks(argument_spec, parameters): |
| 832 |
no_log_values = set() |
| 833 |
for param, value in argument_spec.items(): |
| 834 |
fallback = value.get('fallback', (None,)) |
| 835 |
fallback_strategy = fallback[0] |
| 836 |
fallback_args = [] |
| 837 |
fallback_kwargs = {} |
| 838 |
if param not in parameters and fallback_strategy is not None: |
| 839 |
for item in fallback[1:]: |
| 840 |
if isinstance(item, dict): |
| 841 |
fallback_kwargs = item |
| 842 |
else: |
| 843 |
fallback_args = item |
| 844 |
try: |
| 845 |
fallback_value = fallback_strategy(*fallback_args, **fallback_kwargs) |
| 846 |
except AnsibleFallbackNotFound: |
| 847 |
continue |
| 848 |
else: |
| 849 |
if value.get('no_log', False) and fallback_value: |
| 850 |
no_log_values.add(fallback_value) |
| 851 |
parameters[param] = fallback_value |
| 852 |
|
| 853 |
return no_log_values |
| 854 |
|
| 855 |
|
| 856 |
def sanitize_keys(obj, no_log_strings, ignore_keys=frozenset()): |
| 857 |
"""Sanitize the keys in a container object by removing ``no_log`` values from key names. |
| 858 |
|
| 859 |
This is a companion function to the :func:`remove_values` function. Similar to that function, |
| 860 |
we make use of ``deferred_removals`` to avoid hitting maximum recursion depth in cases of |
| 861 |
large data structures. |
| 862 |
|
| 863 |
:arg obj: The container object to sanitize. Non-container objects are returned unmodified. |
| 864 |
:arg no_log_strings: A set of string values we do not want logged. |
| 865 |
:kwarg ignore_keys: A set of string values of keys to not sanitize. |
| 866 |
|
| 867 |
:returns: An object with sanitized keys. |
| 868 |
""" |
| 869 |
# TODO remove helper functions when removing this function |
| 870 |
_deprecate( |
| 871 |
msg="The `sanitize_keys()` function from `ansible.module_utils.common.parameters` is deprecated.", |
| 872 |
version="2.25", |
| 873 |
help_text="Secret values are now masked automatically. Use functions from `ansible.module_utils.secrets` if you need to handle secrets manually.", |
| 874 |
) |
| 875 |
|
| 876 |
deferred_removals = deque() |
| 877 |
|
| 878 |
# sort ensuring we always handle longer strings vs subsets |
| 879 |
no_log_strings = sorted([to_native(s, errors='surrogate_or_strict') for s in no_log_strings], key=len, reverse=True) |
| 880 |
new_value = _sanitize_keys_conditions(obj, deferred_removals) |
| 881 |
|
| 882 |
while deferred_removals: |
| 883 |
old_data, new_data = deferred_removals.popleft() |
| 884 |
|
| 885 |
if isinstance(new_data, Mapping): |
| 886 |
for old_key, old_elem in old_data.items(): |
| 887 |
if old_key in ignore_keys or old_key.startswith('_ansible'): |
| 888 |
new_data[old_key] = _sanitize_keys_conditions(old_elem, deferred_removals) |
| 889 |
else: |
| 890 |
# Sanitize the old key. We take advantage of the sanitizing code in |
| 891 |
# _remove_values_conditions() rather than recreating it here. |
| 892 |
new_key = _remove_values_conditions(old_key, no_log_strings, None) |
| 893 |
new_data[new_key] = _sanitize_keys_conditions(old_elem, deferred_removals) |
| 894 |
else: |
| 895 |
for elem in old_data: |
| 896 |
new_elem = _sanitize_keys_conditions(elem, deferred_removals) |
| 897 |
if isinstance(new_data, MutableSequence): |
| 898 |
new_data.append(new_elem) |
| 899 |
elif isinstance(new_data, MutableSet): |
| 900 |
new_data.add(new_elem) |
| 901 |
else: |
| 902 |
raise TypeError('Unknown container type encountered when removing private values from keys') |
| 903 |
|
| 904 |
return new_value |
| 905 |
|
| 906 |
|
| 907 |
def remove_values(value, no_log_strings): |
| 908 |
"""Remove strings in ``no_log_strings`` from value. |
| 909 |
|
| 910 |
If value is a container type, then remove a lot more. |
| 911 |
|
| 912 |
Use of ``deferred_removals`` exists, rather than a pure recursive solution, |
| 913 |
because of the potential to hit the maximum recursion depth when dealing with |
| 914 |
large amounts of data (see `issue #24560 <https://github.com/ansible/ansible/issues/24560>`_). |
| 915 |
""" |
| 916 |
# TODO remove helper functions when removing this function |
| 917 |
_deprecate( |
| 918 |
msg="The `remove_values()` function from `ansible.module_utils.common.parameters` is deprecated.", |
| 919 |
version="2.25", |
| 920 |
help_text="Secret values are now masked automatically. Use functions from `ansible.module_utils.secrets` if you need to handle secrets manually.", |
| 921 |
) |
| 922 |
|
| 923 |
deferred_removals = deque() |
| 924 |
|
| 925 |
# sort ensuring we always handle longer strings vs subsets |
| 926 |
no_log_strings = sorted([to_native(s, errors='surrogate_or_strict') for s in no_log_strings], key=len, reverse=True) |
| 927 |
new_value = _remove_values_conditions(value, no_log_strings, deferred_removals) |
| 928 |
|
| 929 |
while deferred_removals: |
| 930 |
old_data, new_data = deferred_removals.popleft() |
| 931 |
if isinstance(new_data, Mapping): |
| 932 |
for old_key, old_elem in old_data.items(): |
| 933 |
new_elem = _remove_values_conditions(old_elem, no_log_strings, deferred_removals) |
| 934 |
new_data[old_key] = new_elem |
| 935 |
else: |
| 936 |
for elem in old_data: |
| 937 |
new_elem = _remove_values_conditions(elem, no_log_strings, deferred_removals) |
| 938 |
if isinstance(new_data, MutableSequence): |
| 939 |
new_data.append(new_elem) |
| 940 |
elif isinstance(new_data, MutableSet): |
| 941 |
new_data.add(new_elem) |
| 942 |
else: |
| 943 |
raise TypeError('Unknown container type encountered when removing private values from output') |
| 944 |
|
| 945 |
return new_value |
| 946 |
|
| 947 |
|
| 948 |
def __getattr__(importable_name): |
| 949 |
return _no_six.deprecate(importable_name, __name__, "binary_type", "text_type", "integer_types", "string_types", "PY2", "PY3") |