| 1 |
# Copyright: (c) 2012-2014, Michael DeHaan <[email protected]> |
| 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 |
|
| 5 |
from __future__ import annotations |
| 6 |
|
| 7 |
import decimal |
| 8 |
import itertools |
| 9 |
import operator |
| 10 |
import os |
| 11 |
|
| 12 |
import typing as t |
| 13 |
|
| 14 |
from copy import copy as shallowcopy |
| 15 |
from functools import cache |
| 16 |
|
| 17 |
from ansible import constants as C |
| 18 |
from ansible import context |
| 19 |
from ansible.errors import AnsibleError, AnsibleParserError, AnsibleAssertionError, AnsibleValueOmittedError, AnsibleFieldAttributeError |
| 20 |
from ansible.module_utils.datatag import native_type_name |
| 21 |
from ansible._internal._datatag._tags import Origin |
| 22 |
from ansible.module_utils.parsing.convert_bool import boolean |
| 23 |
from ansible.module_utils.common.sentinel import Sentinel |
| 24 |
from ansible.module_utils.common.text.converters import to_text |
| 25 |
from ansible.parsing.dataloader import DataLoader |
| 26 |
from ansible.playbook.attribute import Attribute, FieldAttribute, NonInheritableFieldAttribute |
| 27 |
from ansible.plugins.loader import module_loader, action_loader |
| 28 |
from ansible.utils.collection_loader._collection_finder import _get_collection_metadata, AnsibleCollectionRef |
| 29 |
from ansible.utils.display import Display |
| 30 |
from ansible.utils.vars import combine_vars, get_unique_id, validate_variable_name |
| 31 |
from ansible._internal._templating._engine import TemplateEngine |
| 32 |
from ansible._internal import _task |
| 33 |
|
| 34 |
display = Display() |
| 35 |
|
| 36 |
|
| 37 |
def _validate_action_group_metadata(action, found_group_metadata, fq_group_name): |
| 38 |
valid_metadata = { |
| 39 |
'extend_group': { |
| 40 |
'types': (list, str,), |
| 41 |
'errortype': 'list', |
| 42 |
}, |
| 43 |
} |
| 44 |
|
| 45 |
metadata_warnings = [] |
| 46 |
|
| 47 |
validate = C.VALIDATE_ACTION_GROUP_METADATA |
| 48 |
metadata_only = isinstance(action, dict) and 'metadata' in action and len(action) == 1 |
| 49 |
|
| 50 |
if validate and not metadata_only: |
| 51 |
found_keys = ', '.join(sorted(list(action))) |
| 52 |
metadata_warnings.append("The only expected key is metadata, but got keys: {keys}".format(keys=found_keys)) |
| 53 |
elif validate: |
| 54 |
if found_group_metadata: |
| 55 |
metadata_warnings.append("The group contains multiple metadata entries.") |
| 56 |
if not isinstance(action['metadata'], dict): |
| 57 |
metadata_warnings.append("The metadata is not a dictionary. Got {metadata}".format(metadata=action['metadata'])) |
| 58 |
else: |
| 59 |
unexpected_keys = set(action['metadata'].keys()) - set(valid_metadata.keys()) |
| 60 |
if unexpected_keys: |
| 61 |
metadata_warnings.append("The metadata contains unexpected keys: {0}".format(', '.join(unexpected_keys))) |
| 62 |
unexpected_types = [] |
| 63 |
for field, requirement in valid_metadata.items(): |
| 64 |
if field not in action['metadata']: |
| 65 |
continue |
| 66 |
value = action['metadata'][field] |
| 67 |
if not isinstance(value, requirement['types']): |
| 68 |
unexpected_types.append("%s is %s (expected type %s)" % (field, value, requirement['errortype'])) |
| 69 |
if unexpected_types: |
| 70 |
metadata_warnings.append("The metadata contains unexpected key types: {0}".format(', '.join(unexpected_types))) |
| 71 |
if metadata_warnings: |
| 72 |
metadata_warnings.insert(0, "Invalid metadata was found for action_group {0} while loading module_defaults.".format(fq_group_name)) |
| 73 |
display.warning(" ".join(metadata_warnings)) |
| 74 |
|
| 75 |
|
| 76 |
class _ClassProperty: |
| 77 |
def __set_name__(self, owner, name): |
| 78 |
self.name = name |
| 79 |
|
| 80 |
def __get__(self, obj, objtype=None): |
| 81 |
return getattr(objtype, f'_{self.name}')() |
| 82 |
|
| 83 |
|
| 84 |
class FieldAttributeBase: |
| 85 |
|
| 86 |
_post_validate_object = False |
| 87 |
""" |
| 88 |
`False` skips FieldAttribute post-validation on intermediate objects and mixins for attributes without `always_post_validate`. |
| 89 |
Leaf objects (e.g., `Task`) should set this attribute `True` to opt-in to post-validation. |
| 90 |
""" |
| 91 |
fattributes = _ClassProperty() |
| 92 |
|
| 93 |
@classmethod |
| 94 |
@cache |
| 95 |
def _fattributes(cls): |
| 96 |
fattributes = {} |
| 97 |
for class_obj in reversed(cls.__mro__): |
| 98 |
for name, attr in list(class_obj.__dict__.items()): |
| 99 |
if not isinstance(attr, Attribute): |
| 100 |
continue |
| 101 |
fattributes[name] = attr |
| 102 |
if attr.alias: |
| 103 |
setattr(class_obj, attr.alias, attr) |
| 104 |
fattributes[attr.alias] = attr |
| 105 |
return fattributes |
| 106 |
|
| 107 |
def __init__(self) -> None: |
| 108 |
|
| 109 |
# initialize the data loader and variable manager, which will be provided |
| 110 |
# later when the object is actually loaded |
| 111 |
self._loader = None |
| 112 |
self._variable_manager = None |
| 113 |
self._origin: Origin | None = None |
| 114 |
|
| 115 |
# other internal params |
| 116 |
self._validated = False |
| 117 |
self._squashed = False |
| 118 |
self._finalized = False |
| 119 |
|
| 120 |
# every object gets a random uuid: |
| 121 |
self._uuid = get_unique_id() |
| 122 |
|
| 123 |
@property |
| 124 |
def finalized(self): |
| 125 |
return self._finalized |
| 126 |
|
| 127 |
def dump_me(self, depth=0): |
| 128 |
""" this is never called from production code, it is here to be used when debugging as a 'complex print' """ |
| 129 |
if depth == 0: |
| 130 |
display.debug("DUMPING OBJECT ------------------------------------------------------") |
| 131 |
display.debug("%s- %s (%s, id=%s)" % (" " * depth, self.__class__.__name__, self, id(self))) |
| 132 |
if hasattr(self, '_parent') and self._parent: |
| 133 |
self._parent.dump_me(depth + 2) |
| 134 |
dep_chain = self._parent.get_dep_chain() |
| 135 |
if dep_chain: |
| 136 |
for dep in dep_chain: |
| 137 |
dep.dump_me(depth + 2) |
| 138 |
if hasattr(self, '_play') and self._play: |
| 139 |
self._play.dump_me(depth + 2) |
| 140 |
|
| 141 |
def preprocess_data(self, ds): |
| 142 |
""" infrequently used method to do some pre-processing of legacy terms """ |
| 143 |
return ds |
| 144 |
|
| 145 |
def load_data(self, ds, variable_manager=None, loader=None): |
| 146 |
""" walk the input datastructure and assign any values """ |
| 147 |
|
| 148 |
if ds is None: |
| 149 |
raise AnsibleAssertionError('ds (%s) should not be None but it is.' % ds) |
| 150 |
|
| 151 |
# cache the datastructure internally |
| 152 |
setattr(self, '_ds', ds) |
| 153 |
|
| 154 |
# the variable manager class is used to manage and merge variables |
| 155 |
# down to a single dictionary for reference in templating, etc. |
| 156 |
self._variable_manager = variable_manager |
| 157 |
self._origin = Origin.get_tag(ds) |
| 158 |
|
| 159 |
# the data loader class is used to parse data from strings and files |
| 160 |
if loader is not None: |
| 161 |
self._loader = loader |
| 162 |
else: |
| 163 |
self._loader = DataLoader() |
| 164 |
|
| 165 |
# call the preprocess_data() function to massage the data into |
| 166 |
# something we can more easily parse, and then call the validation |
| 167 |
# function on it to ensure there are no incorrect key values |
| 168 |
ds = self.preprocess_data(ds) |
| 169 |
self._validate_attributes(ds) |
| 170 |
|
| 171 |
# Walk all attributes in the class. We sort them based on their priority |
| 172 |
# so that certain fields can be loaded before others, if they are dependent. |
| 173 |
for name, attr in sorted(self.fattributes.items(), key=operator.itemgetter(1)): |
| 174 |
# copy the value over unless a _load_field method is defined |
| 175 |
if name in ds: |
| 176 |
method = getattr(self, '_load_%s' % name, None) |
| 177 |
if method: |
| 178 |
setattr(self, name, method(name, ds[name])) |
| 179 |
else: |
| 180 |
setattr(self, name, ds[name]) |
| 181 |
|
| 182 |
# run early, non-critical validation |
| 183 |
self.validate() |
| 184 |
|
| 185 |
# return the constructed object |
| 186 |
return self |
| 187 |
|
| 188 |
def get_ds(self): |
| 189 |
try: |
| 190 |
return self._ds |
| 191 |
except AttributeError: |
| 192 |
return None |
| 193 |
|
| 194 |
def get_loader(self): |
| 195 |
return self._loader |
| 196 |
|
| 197 |
def get_variable_manager(self): |
| 198 |
return self._variable_manager |
| 199 |
|
| 200 |
def _post_validate_debugger(self, attr, value, templar): |
| 201 |
try: |
| 202 |
value = templar.template(value) |
| 203 |
except AnsibleValueOmittedError: |
| 204 |
value = self.set_to_context(attr.name) |
| 205 |
|
| 206 |
valid_values = frozenset(('always', 'on_failed', 'on_unreachable', 'on_skipped', 'never')) |
| 207 |
if value and isinstance(value, str) and value not in valid_values: |
| 208 |
raise AnsibleParserError("'%s' is not a valid value for debugger. Must be one of %s" % (value, ', '.join(valid_values)), obj=self.get_ds()) |
| 209 |
return value |
| 210 |
|
| 211 |
def _validate_attributes(self, ds): |
| 212 |
""" |
| 213 |
Ensures that there are no keys in the datastructure which do |
| 214 |
not map to attributes for this object. |
| 215 |
""" |
| 216 |
|
| 217 |
valid_attrs = frozenset(self.fattributes) |
| 218 |
for key in ds: |
| 219 |
if key not in valid_attrs: |
| 220 |
raise AnsibleParserError("'%s' is not a valid attribute for a %s" % (key, self.__class__.__name__), obj=key) |
| 221 |
|
| 222 |
def validate(self, all_vars=None): |
| 223 |
""" validation that is done at parse time, not load time """ |
| 224 |
if not self._validated: |
| 225 |
# walk all fields in the object |
| 226 |
for (name, attribute) in self.fattributes.items(): |
| 227 |
# run validator only if present |
| 228 |
method = getattr(self, '_validate_%s' % name, None) |
| 229 |
if method: |
| 230 |
method(attribute, name, getattr(self, name)) |
| 231 |
else: |
| 232 |
# and make sure the attribute is of the type it should be |
| 233 |
value = getattr(self, f'_{name}', Sentinel) |
| 234 |
if value is not None: |
| 235 |
if attribute.isa == 'string' and isinstance(value, (list, dict)): |
| 236 |
raise AnsibleParserError( |
| 237 |
"The field '%s' is supposed to be a string type," |
| 238 |
" however the incoming data structure is a %s" % (name, type(value)), obj=value |
| 239 |
) |
| 240 |
|
| 241 |
self._validated = True |
| 242 |
|
| 243 |
def _load_module_defaults(self, name, value): |
| 244 |
if value is None: |
| 245 |
return |
| 246 |
|
| 247 |
if not isinstance(value, list): |
| 248 |
value = [value] |
| 249 |
|
| 250 |
validated_module_defaults = [] |
| 251 |
for defaults_dict in value: |
| 252 |
if not isinstance(defaults_dict, dict): |
| 253 |
raise AnsibleParserError( |
| 254 |
"The field 'module_defaults' is supposed to be a dictionary or list of dictionaries, " |
| 255 |
"the keys of which must be static action, module, or group names. Only the values may contain " |
| 256 |
"templates. For example: {'ping': \"{{ ping_defaults }}\"}", |
| 257 |
obj=defaults_dict, |
| 258 |
) |
| 259 |
|
| 260 |
validated_defaults_dict = {} |
| 261 |
for defaults_entry, defaults in defaults_dict.items(): |
| 262 |
# module_defaults do not use the 'collections' keyword, so actions and |
| 263 |
# action_groups that are not fully qualified are part of the 'ansible.legacy' |
| 264 |
# collection. Update those entries here, so module_defaults contains |
| 265 |
# fully qualified entries. |
| 266 |
if defaults_entry.startswith('group/'): |
| 267 |
group_name = defaults_entry.split('group/')[-1] |
| 268 |
|
| 269 |
# The resolved action_groups cache is associated saved on the current Play |
| 270 |
if self.play is not None: |
| 271 |
group_name, dummy = self._resolve_group(group_name) |
| 272 |
|
| 273 |
defaults_entry = 'group/' + group_name |
| 274 |
validated_defaults_dict[defaults_entry] = defaults |
| 275 |
|
| 276 |
else: |
| 277 |
if len(defaults_entry.split('.')) < 3: |
| 278 |
defaults_entry = 'ansible.legacy.' + defaults_entry |
| 279 |
|
| 280 |
resolved_action = self._resolve_action(defaults_entry) |
| 281 |
if resolved_action: |
| 282 |
validated_defaults_dict[resolved_action] = defaults |
| 283 |
|
| 284 |
# If the defaults_entry is an ansible.legacy plugin, these defaults |
| 285 |
# are inheritable by the 'ansible.builtin' subset, but are not |
| 286 |
# required to exist. |
| 287 |
if defaults_entry.startswith('ansible.legacy.'): |
| 288 |
resolved_action = self._resolve_action( |
| 289 |
defaults_entry.replace('ansible.legacy.', 'ansible.builtin.'), |
| 290 |
mandatory=False |
| 291 |
) |
| 292 |
if resolved_action: |
| 293 |
validated_defaults_dict[resolved_action] = defaults |
| 294 |
|
| 295 |
validated_module_defaults.append(validated_defaults_dict) |
| 296 |
|
| 297 |
return validated_module_defaults |
| 298 |
|
| 299 |
@property |
| 300 |
def play(self): |
| 301 |
if hasattr(self, '_play'): |
| 302 |
play = self._play |
| 303 |
elif hasattr(self, '_parent') and hasattr(self._parent, '_play'): |
| 304 |
play = self._parent._play |
| 305 |
else: |
| 306 |
play = self |
| 307 |
|
| 308 |
if play.__class__.__name__ != 'Play': |
| 309 |
# Should never happen, but handle gracefully by returning None, just in case |
| 310 |
return None |
| 311 |
|
| 312 |
return play |
| 313 |
|
| 314 |
def _resolve_group(self, fq_group_name, mandatory=True): |
| 315 |
if not AnsibleCollectionRef.is_valid_fqcr(fq_group_name): |
| 316 |
collection_name = 'ansible.builtin' |
| 317 |
fq_group_name = collection_name + '.' + fq_group_name |
| 318 |
else: |
| 319 |
collection_name = '.'.join(fq_group_name.split('.')[0:2]) |
| 320 |
|
| 321 |
# Check if the group has already been resolved and cached |
| 322 |
if fq_group_name in self.play._group_actions: |
| 323 |
return fq_group_name, self.play._group_actions[fq_group_name] |
| 324 |
|
| 325 |
try: |
| 326 |
action_groups = _get_collection_metadata(collection_name).get('action_groups', {}) |
| 327 |
except ValueError: |
| 328 |
if not mandatory: |
| 329 |
display.vvvvv("Error loading module_defaults: could not resolve the module_defaults group %s" % fq_group_name) |
| 330 |
return fq_group_name, [] |
| 331 |
|
| 332 |
raise AnsibleParserError("Error loading module_defaults: could not resolve the module_defaults group %s" % fq_group_name) |
| 333 |
|
| 334 |
# The collection may or may not use the fully qualified name |
| 335 |
# Don't fail if the group doesn't exist in the collection |
| 336 |
resource_name = fq_group_name.split(collection_name + '.')[-1] |
| 337 |
action_group = action_groups.get( |
| 338 |
fq_group_name, |
| 339 |
action_groups.get(resource_name) |
| 340 |
) |
| 341 |
if action_group is None: |
| 342 |
if not mandatory: |
| 343 |
display.vvvvv("Error loading module_defaults: could not resolve the module_defaults group %s" % fq_group_name) |
| 344 |
return fq_group_name, [] |
| 345 |
raise AnsibleParserError("Error loading module_defaults: could not resolve the module_defaults group %s" % fq_group_name) |
| 346 |
|
| 347 |
resolved_actions = [] |
| 348 |
include_groups = [] |
| 349 |
|
| 350 |
found_group_metadata = False |
| 351 |
for action in action_group: |
| 352 |
# Everything should be a string except the metadata entry |
| 353 |
if not isinstance(action, str): |
| 354 |
_validate_action_group_metadata(action, found_group_metadata, fq_group_name) |
| 355 |
|
| 356 |
if isinstance(action['metadata'], dict): |
| 357 |
found_group_metadata = True |
| 358 |
|
| 359 |
include_groups = action['metadata'].get('extend_group', []) |
| 360 |
if isinstance(include_groups, str): |
| 361 |
include_groups = [include_groups] |
| 362 |
if not isinstance(include_groups, list): |
| 363 |
# Bad entries may be a warning above, but prevent tracebacks by setting it back to the acceptable type. |
| 364 |
include_groups = [] |
| 365 |
continue |
| 366 |
|
| 367 |
# The collection may or may not use the fully qualified name. |
| 368 |
# If not, it's part of the current collection. |
| 369 |
if not AnsibleCollectionRef.is_valid_fqcr(action): |
| 370 |
action = collection_name + '.' + action |
| 371 |
resolved_action = self._resolve_action(action, mandatory=False) |
| 372 |
if resolved_action: |
| 373 |
resolved_actions.append(resolved_action) |
| 374 |
|
| 375 |
for action in resolved_actions: |
| 376 |
if action not in self.play._action_groups: |
| 377 |
self.play._action_groups[action] = [] |
| 378 |
self.play._action_groups[action].append(fq_group_name) |
| 379 |
|
| 380 |
self.play._group_actions[fq_group_name] = resolved_actions |
| 381 |
|
| 382 |
# Resolve extended groups last, after caching the group in case they recursively refer to each other |
| 383 |
for include_group in include_groups: |
| 384 |
if not AnsibleCollectionRef.is_valid_fqcr(include_group): |
| 385 |
include_group = collection_name + '.' + include_group |
| 386 |
|
| 387 |
dummy, group_actions = self._resolve_group(include_group, mandatory=False) |
| 388 |
|
| 389 |
for action in group_actions: |
| 390 |
if action not in self.play._action_groups: |
| 391 |
self.play._action_groups[action] = [] |
| 392 |
self.play._action_groups[action].append(fq_group_name) |
| 393 |
|
| 394 |
self.play._group_actions[fq_group_name].extend(group_actions) |
| 395 |
resolved_actions.extend(group_actions) |
| 396 |
|
| 397 |
return fq_group_name, resolved_actions |
| 398 |
|
| 399 |
def _resolve_action(self, action_name, mandatory=True): |
| 400 |
context = module_loader.find_plugin_with_context(action_name, ignore_deprecated=(not mandatory)) |
| 401 |
if context.resolved and not context.action_plugin: |
| 402 |
prefer = action_loader.find_plugin_with_context(action_name, ignore_deprecated=(not mandatory)) |
| 403 |
if prefer.resolved: |
| 404 |
context = prefer |
| 405 |
elif not context.resolved: |
| 406 |
context = action_loader.find_plugin_with_context(action_name, ignore_deprecated=(not mandatory)) |
| 407 |
|
| 408 |
if context.resolved: |
| 409 |
return context.resolved_fqcn |
| 410 |
if mandatory: |
| 411 |
raise AnsibleParserError("Could not resolve action %s in module_defaults" % action_name) |
| 412 |
display.vvvvv("Could not resolve action %s in module_defaults" % action_name) |
| 413 |
|
| 414 |
def squash(self): |
| 415 |
""" |
| 416 |
Evaluates all attributes and sets them to the evaluated version, |
| 417 |
so that all future accesses of attributes do not need to evaluate |
| 418 |
parent attributes. |
| 419 |
""" |
| 420 |
if not self._squashed: |
| 421 |
for name in self.fattributes: |
| 422 |
setattr(self, name, getattr(self, name)) |
| 423 |
self._squashed = True |
| 424 |
|
| 425 |
def copy(self): |
| 426 |
""" |
| 427 |
Create a copy of this object and return it. |
| 428 |
""" |
| 429 |
|
| 430 |
try: |
| 431 |
new_me = self.__class__() |
| 432 |
except RecursionError as ex: |
| 433 |
raise AnsibleError("Exceeded maximum object depth. This may have been caused by excessive role recursion.") from ex |
| 434 |
|
| 435 |
for name in self.fattributes: |
| 436 |
setattr(new_me, name, shallowcopy(getattr(self, f'_{name}', Sentinel))) |
| 437 |
|
| 438 |
new_me._loader = self._loader |
| 439 |
new_me._variable_manager = self._variable_manager |
| 440 |
new_me._origin = self._origin |
| 441 |
new_me._validated = self._validated |
| 442 |
new_me._finalized = self._finalized |
| 443 |
new_me._uuid = self._uuid |
| 444 |
|
| 445 |
# if the ds value was set on the object, copy it to the new copy too |
| 446 |
if hasattr(self, '_ds'): |
| 447 |
new_me._ds = self._ds |
| 448 |
|
| 449 |
return new_me |
| 450 |
|
| 451 |
def get_validated_value(self, name, attribute, value, templar): |
| 452 |
try: |
| 453 |
return self._get_validated_value(name, attribute, value, templar) |
| 454 |
except (TypeError, ValueError): |
| 455 |
raise AnsibleError(f"The value {value!r} could not be converted to {attribute.isa!r}.", obj=value) |
| 456 |
|
| 457 |
def _get_validated_value(self, name, attribute, value, templar): |
| 458 |
if attribute.isa == 'string': |
| 459 |
value = to_text(value) |
| 460 |
elif attribute.isa == 'int': |
| 461 |
if not isinstance(value, int): |
| 462 |
try: |
| 463 |
if (decimal_value := decimal.Decimal(value)) != (int_value := int(decimal_value)): |
| 464 |
raise decimal.DecimalException(f'Floating-point value {value!r} would be truncated.') |
| 465 |
value = int_value |
| 466 |
except decimal.DecimalException as e: |
| 467 |
raise ValueError from e |
| 468 |
elif attribute.isa == 'float': |
| 469 |
value = float(value) |
| 470 |
elif attribute.isa == 'bool': |
| 471 |
value = boolean(value, strict=True) |
| 472 |
elif attribute.isa == 'percent': |
| 473 |
# special value, which may be an integer or float |
| 474 |
# with an optional '%' at the end |
| 475 |
if isinstance(value, str) and '%' in value: |
| 476 |
value = value.replace('%', '') |
| 477 |
value = float(value) |
| 478 |
elif attribute.isa == 'list': |
| 479 |
if value is None: |
| 480 |
value = [] |
| 481 |
elif not isinstance(value, list): |
| 482 |
value = [value] |
| 483 |
if attribute.listof is not None: |
| 484 |
for item in value: |
| 485 |
if not isinstance(item, attribute.listof): |
| 486 |
type_names = ' or '.join(f'{native_type_name(attribute_type)!r}' for attribute_type in attribute.listof) |
| 487 |
|
| 488 |
raise AnsibleParserError( |
| 489 |
message=f"Keyword {name!r} items must be of type {type_names}, not {native_type_name(item)!r}.", |
| 490 |
obj=Origin.first_tagged_on(item, value, self.get_ds()), |
| 491 |
) |
| 492 |
elif attribute.required and attribute.listof == (str,): |
| 493 |
if item is None or item.strip() == "": |
| 494 |
raise AnsibleParserError( |
| 495 |
message=f"Keyword {name!r} is required, and cannot have empty values.", |
| 496 |
obj=Origin.first_tagged_on(item, value, self.get_ds()), |
| 497 |
) |
| 498 |
elif attribute.isa == 'dict': |
| 499 |
if value is None: |
| 500 |
value = dict() |
| 501 |
elif not isinstance(value, dict): |
| 502 |
raise AnsibleError(f"{value!r} is not a dictionary") |
| 503 |
elif attribute.isa == 'class': |
| 504 |
if not isinstance(value, attribute.class_type): |
| 505 |
raise TypeError("%s is not a valid %s (got a %s instead)" % (name, attribute.class_type, type(value))) |
| 506 |
value.post_validate(templar=templar) |
| 507 |
else: |
| 508 |
raise AnsibleAssertionError(f"Unknown value for attribute.isa: {attribute.isa}") |
| 509 |
return value |
| 510 |
|
| 511 |
def set_to_context(self, name: str) -> t.Any: |
| 512 |
""" set to parent inherited value or Sentinel as appropriate""" |
| 513 |
|
| 514 |
attribute = self.fattributes[name] |
| 515 |
if isinstance(attribute, NonInheritableFieldAttribute): |
| 516 |
# setting to sentinel will trigger 'default/default()' on getter |
| 517 |
value = Sentinel |
| 518 |
else: |
| 519 |
try: |
| 520 |
value = self._get_parent_attribute(name, omit=True) |
| 521 |
except AttributeError: |
| 522 |
# mostly playcontext as only tasks/handlers/blocks really resolve parent |
| 523 |
value = Sentinel |
| 524 |
|
| 525 |
setattr(self, name, value) |
| 526 |
return value |
| 527 |
|
| 528 |
def post_validate(self, templar: TemplateEngine) -> None: |
| 529 |
""" |
| 530 |
we can't tell that everything is of the right type until we have |
| 531 |
all the variables. Run basic types (from isa) as well as |
| 532 |
any _post_validate_<foo> functions. |
| 533 |
""" |
| 534 |
|
| 535 |
for name in self.fattributes: |
| 536 |
value = self.post_validate_attribute(name, templar=templar) |
| 537 |
|
| 538 |
if value is not Sentinel: |
| 539 |
# and assign the massaged value back to the attribute field |
| 540 |
setattr(self, name, value) |
| 541 |
|
| 542 |
self._finalized = True |
| 543 |
|
| 544 |
def post_validate_attribute(self, name: str, *, templar: TemplateEngine): |
| 545 |
attribute: FieldAttribute = self.fattributes[name] |
| 546 |
|
| 547 |
# DTFIX-FUTURE: this can probably be used in many getattr cases below, but the value may be out-of-date in some cases |
| 548 |
original_value = getattr(self, name) # we save this original (likely Origin-tagged) value to pass as `obj` for errors |
| 549 |
|
| 550 |
if attribute.static: |
| 551 |
value = getattr(self, name) |
| 552 |
|
| 553 |
# we don't template 'vars' but allow template as values for later use |
| 554 |
if name not in ('vars',) and templar.is_template(value): |
| 555 |
display.warning('"%s" is not templatable, but we found: %s, ' |
| 556 |
'it will not be templated and will be used "as is".' % (name, value)) |
| 557 |
return Sentinel |
| 558 |
|
| 559 |
if getattr(self, name) is None: |
| 560 |
if not attribute.required: |
| 561 |
return Sentinel |
| 562 |
|
| 563 |
raise AnsibleFieldAttributeError(f'The field {name!r} is required but was not set.', obj=self.get_ds()) |
| 564 |
|
| 565 |
from .role_include import IncludeRole |
| 566 |
|
| 567 |
if not attribute.always_post_validate and isinstance(self, IncludeRole) and self.statically_loaded: # import_role |
| 568 |
# normal field attributes should not go through post validation on import_role/import_tasks |
| 569 |
# only import_role is checked here because import_tasks never reaches this point |
| 570 |
return Sentinel |
| 571 |
|
| 572 |
# Skip post validation unless always_post_validate is True, or the object requires post validation. |
| 573 |
if not attribute.always_post_validate and not self._post_validate_object: |
| 574 |
# Intermediate objects like Play() won't have their fields validated by |
| 575 |
# default, as their values are often inherited by other objects and validated |
| 576 |
# later, so we don't want them to fail out early |
| 577 |
return Sentinel |
| 578 |
|
| 579 |
try: |
| 580 |
# Run the post-validator if present. These methods are responsible for |
| 581 |
# using the given templar to template the values, if required. |
| 582 |
method = getattr(self, '_post_validate_%s' % name, None) |
| 583 |
|
| 584 |
if method: |
| 585 |
value = method(attribute, getattr(self, name), templar) |
| 586 |
elif attribute.isa == 'class': |
| 587 |
value = getattr(self, name) |
| 588 |
else: |
| 589 |
try: |
| 590 |
# if the attribute contains a variable, template it now |
| 591 |
value = templar.template(getattr(self, name)) |
| 592 |
except AnsibleValueOmittedError: |
| 593 |
# If this evaluated to the omit value, set the value back to inherited by context |
| 594 |
# or default specified in the FieldAttribute and move on |
| 595 |
value = self.set_to_context(name) |
| 596 |
|
| 597 |
if value is Sentinel: |
| 598 |
return value |
| 599 |
|
| 600 |
# and make sure the attribute is of the type it should be |
| 601 |
if value is not None: |
| 602 |
value = self.get_validated_value(name, attribute, value, templar) |
| 603 |
|
| 604 |
# returning the value results in assigning the massaged value back to the attribute field |
| 605 |
return value |
| 606 |
except Exception as ex: |
| 607 |
if name == 'args': |
| 608 |
raise # no useful information to contribute, raise the original exception |
| 609 |
|
| 610 |
raise AnsibleFieldAttributeError(f'Error processing keyword {name!r}.', obj=original_value) from ex |
| 611 |
|
| 612 |
def _load_vars(self, attr, ds): |
| 613 |
""" |
| 614 |
Vars in a play must be specified as a dictionary. |
| 615 |
""" |
| 616 |
|
| 617 |
try: |
| 618 |
if isinstance(ds, dict): |
| 619 |
for key in ds: |
| 620 |
validate_variable_name(key) |
| 621 |
return combine_vars(self.vars, ds) |
| 622 |
elif ds is None: |
| 623 |
return {} |
| 624 |
else: |
| 625 |
raise ValueError |
| 626 |
except ValueError as ex: |
| 627 |
raise AnsibleParserError(f"Vars in a {self.__class__.__name__} must be specified as a dictionary.", obj=ds) from ex |
| 628 |
except TypeError as ex: |
| 629 |
raise AnsibleParserError(f"Invalid variable name in vars specified for {self.__class__.__name__}.", obj=ds) from ex |
| 630 |
|
| 631 |
def _extend_value(self, value, new_value, prepend=False): |
| 632 |
""" |
| 633 |
Will extend the value given with new_value (and will turn both |
| 634 |
into lists if they are not so already). The values are run through |
| 635 |
a set to remove duplicate values. |
| 636 |
""" |
| 637 |
|
| 638 |
if not isinstance(value, list): |
| 639 |
value = [value] |
| 640 |
if not isinstance(new_value, list): |
| 641 |
new_value = [new_value] |
| 642 |
|
| 643 |
# Due to where _extend_value may run for some attributes |
| 644 |
# it is possible to end up with Sentinel in the list of values |
| 645 |
# ensure we strip them |
| 646 |
value = [v for v in value if v is not Sentinel] |
| 647 |
new_value = [v for v in new_value if v is not Sentinel] |
| 648 |
|
| 649 |
if prepend: |
| 650 |
combined = new_value + value |
| 651 |
else: |
| 652 |
combined = value + new_value |
| 653 |
|
| 654 |
return [i for i, dummy in itertools.groupby(combined) if i is not None] |
| 655 |
|
| 656 |
def dump_attrs(self): |
| 657 |
""" |
| 658 |
Dumps all attributes to a dictionary |
| 659 |
""" |
| 660 |
attrs = {} |
| 661 |
for (name, attribute) in self.fattributes.items(): |
| 662 |
attr = getattr(self, name) |
| 663 |
if attribute.isa == 'class': |
| 664 |
attrs[name] = attr.dump_attrs() |
| 665 |
else: |
| 666 |
attrs[name] = attr |
| 667 |
return attrs |
| 668 |
|
| 669 |
def from_attrs(self, attrs): |
| 670 |
""" |
| 671 |
Loads attributes from a dictionary |
| 672 |
""" |
| 673 |
for (attr, value) in attrs.items(): |
| 674 |
if attr in self.fattributes: |
| 675 |
attribute = self.fattributes[attr] |
| 676 |
if attribute.isa == 'class' and isinstance(value, dict): |
| 677 |
obj = attribute.class_type() |
| 678 |
obj.from_attrs(value) |
| 679 |
setattr(self, attr, obj) |
| 680 |
else: |
| 681 |
setattr(self, attr, value) |
| 682 |
else: |
| 683 |
setattr(self, attr, value) # overridden dump_attrs in derived types may dump attributes which are not field attributes |
| 684 |
|
| 685 |
|
| 686 |
class Base(FieldAttributeBase): |
| 687 |
|
| 688 |
name = NonInheritableFieldAttribute(isa='string', default='', always_post_validate=True) |
| 689 |
|
| 690 |
# connection/transport |
| 691 |
connection = FieldAttribute(isa='string', default=context.cliargs_deferred_get('connection')) |
| 692 |
port = FieldAttribute(isa='int') |
| 693 |
remote_user = FieldAttribute(isa='string', default=context.cliargs_deferred_get('remote_user')) |
| 694 |
|
| 695 |
# variables |
| 696 |
vars = NonInheritableFieldAttribute(isa='dict', priority=100, static=True, default=dict) |
| 697 |
|
| 698 |
# module default params |
| 699 |
module_defaults = FieldAttribute(isa='list', extend=True, prepend=True) |
| 700 |
|
| 701 |
# flags and misc. settings |
| 702 |
environment = FieldAttribute(isa='list', extend=True, prepend=True) |
| 703 |
no_log = FieldAttribute(isa='bool', default=C.DEFAULT_NO_LOG) |
| 704 |
run_once = FieldAttribute(isa='bool') |
| 705 |
ignore_errors = FieldAttribute(isa='bool') |
| 706 |
ignore_unreachable = FieldAttribute(isa='bool') |
| 707 |
check_mode = FieldAttribute(isa='bool', default=context.cliargs_deferred_get('check')) |
| 708 |
diff = FieldAttribute(isa='bool', default=context.cliargs_deferred_get('diff')) |
| 709 |
any_errors_fatal = FieldAttribute(isa='bool', default=C.ANY_ERRORS_FATAL) |
| 710 |
throttle = FieldAttribute(isa='int', default=0) |
| 711 |
timeout = FieldAttribute(isa='int', default=C.TASK_TIMEOUT) |
| 712 |
|
| 713 |
# explicitly invoke a debugger on tasks |
| 714 |
debugger = FieldAttribute(isa='string') |
| 715 |
|
| 716 |
# Privilege escalation |
| 717 |
become = FieldAttribute(isa='bool', default=context.cliargs_deferred_get('become')) |
| 718 |
become_method = FieldAttribute(isa='string', default=context.cliargs_deferred_get('become_method')) |
| 719 |
become_user = FieldAttribute(isa='string', default=context.cliargs_deferred_get('become_user')) |
| 720 |
become_flags = FieldAttribute(isa='string', default=context.cliargs_deferred_get('become_flags')) |
| 721 |
become_exe = FieldAttribute(isa='string', default=context.cliargs_deferred_get('become_exe')) |
| 722 |
|
| 723 |
# used to hold sudo/su stuff |
| 724 |
DEPRECATED_ATTRIBUTES = [] # type: list[str] |
| 725 |
|
| 726 |
def update_result_no_log(self, templar: TemplateEngine, utr: _task.UnifiedTaskResult) -> None: |
| 727 |
"""Set the post-validated no_log value for the result, falling back to a default on validation/templating failure with a warning.""" |
| 728 |
# RPFIX-9: FUTURE: consolidate this into UTR |
| 729 |
|
| 730 |
if self.finalized: |
| 731 |
no_log = self.no_log |
| 732 |
else: |
| 733 |
try: |
| 734 |
no_log = self.post_validate_attribute('no_log', templar=templar) |
| 735 |
except Exception as ex: |
| 736 |
display.error_as_warning('Invalid no_log value for task, output will be masked.', exception=ex) |
| 737 |
no_log = True |
| 738 |
|
| 739 |
result_no_log = utr.no_log |
| 740 |
|
| 741 |
utr.no_log = no_log or result_no_log |
| 742 |
|
| 743 |
def get_path(self) -> str: |
| 744 |
""" return the absolute path of the playbook object and its line number """ |
| 745 |
origin = self._origin |
| 746 |
|
| 747 |
if not origin: |
| 748 |
try: |
| 749 |
origin = self._parent._play._origin |
| 750 |
except AttributeError: |
| 751 |
pass |
| 752 |
|
| 753 |
if origin and origin.path: |
| 754 |
path = f"{origin.path}:{origin.line_num or 1}" |
| 755 |
else: |
| 756 |
path = "" |
| 757 |
|
| 758 |
return path |
| 759 |
|
| 760 |
def get_dep_chain(self): |
| 761 |
|
| 762 |
if hasattr(self, '_parent') and self._parent: |
| 763 |
return self._parent.get_dep_chain() |
| 764 |
else: |
| 765 |
return None |
| 766 |
|
| 767 |
def get_search_path(self): |
| 768 |
""" |
| 769 |
Return the list of paths you should search for files, in order. |
| 770 |
This follows role/playbook dependency chain. |
| 771 |
""" |
| 772 |
path_stack = [] |
| 773 |
|
| 774 |
dep_chain = self.get_dep_chain() |
| 775 |
# inside role: add the dependency chain from current to dependent |
| 776 |
if dep_chain: |
| 777 |
path_stack.extend(reversed([x._role_path for x in dep_chain if hasattr(x, '_role_path')])) |
| 778 |
|
| 779 |
# add path of task itself, unless it is already in the list |
| 780 |
task_dir = os.path.dirname(self.get_path()) |
| 781 |
if task_dir not in path_stack: |
| 782 |
path_stack.append(task_dir) |
| 783 |
|
| 784 |
return path_stack |