| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import contextlib |
| 4 |
import dataclasses |
| 5 |
import enum |
| 6 |
import functools |
| 7 |
import types |
| 8 |
import typing as t |
| 9 |
|
| 10 |
from collections import abc as c |
| 11 |
|
| 12 |
from ansible._internal import _display_utils |
| 13 |
from ansible._internal._errors import _attribute_unavailable, _captured, _error_factory, _error_utils |
| 14 |
from ansible._internal._templating import _engine |
| 15 |
from ansible._internal._templating._chain_templar import ChainTemplar |
| 16 |
from ansible._internal._worker import _inventory_rpc |
| 17 |
from ansible._internal._datatag import _tags |
| 18 |
from ansible.errors import AnsibleError, AnsibleTemplateError |
| 19 |
from ansible.module_utils._internal._ambient_context import AmbientContextBase |
| 20 |
from ansible.module_utils._internal import _dataclass_validation, _event_utils, _messages, _secrets, _traceback |
| 21 |
from ansible.module_utils.common.text.converters import to_text |
| 22 |
from ansible.module_utils.datatag import native_type_name, deprecator_from_collection_name, deprecate_value |
| 23 |
from ansible.module_utils.secrets import register_secrets |
| 24 |
from ansible.parsing import vault as _vault |
| 25 |
from ansible.template import trust_as_template |
| 26 |
from ansible.utils.display import Display |
| 27 |
from ansible.utils import vars as _vars |
| 28 |
|
| 29 |
if t.TYPE_CHECKING: |
| 30 |
from ansible.playbook.task import Task |
| 31 |
from ansible.inventory.host import Host |
| 32 |
from ansible.executor.task_executor import TaskExecutor |
| 33 |
|
| 34 |
display = Display() |
| 35 |
|
| 36 |
PRESERVE = frozenset( |
| 37 |
{ |
| 38 |
'_ansible_no_log', |
| 39 |
'attempts', |
| 40 |
'changed', |
| 41 |
'deprecations', |
| 42 |
'exception', |
| 43 |
'retries', |
| 44 |
'warnings', |
| 45 |
} |
| 46 |
) |
| 47 |
|
| 48 |
POLYMORPHIC_RESULT_EXPRESSION = trust_as_template("_task.polymorphic_result") |
| 49 |
|
| 50 |
|
| 51 |
class NoRecordedResultError(AnsibleError): |
| 52 |
"""Error raised when requesting recorded results prior to any being recorded.""" |
| 53 |
|
| 54 |
_default_message = "No task result has been recorded." |
| 55 |
|
| 56 |
|
| 57 |
class NotALoopError(AnsibleError): |
| 58 |
"""Error raised when attempting to access loop state when not in a loop.""" |
| 59 |
|
| 60 |
_default_message = "The current task is not a loop." |
| 61 |
|
| 62 |
|
| 63 |
@dataclasses.dataclass(kw_only=True, slots=True) |
| 64 |
class CurrentTask: |
| 65 |
""" |
| 66 |
Instances of this type are exposed to Jinja during register projections and playbook conditional expression eval. |
| 67 |
|
| 68 |
CAUTION: The shape and behavior of this type is effectively public API. |
| 69 |
""" |
| 70 |
|
| 71 |
def _lazy_transform(self, value: t.Any) -> t.Any: |
| 72 |
"""Lazily transform the given value.""" |
| 73 |
return TaskContext.current().task_templar.template(value, lazy_options=_engine.LazyOptions.SKIP_TEMPLATES_AND_ACCESS) |
| 74 |
|
| 75 |
@property |
| 76 |
def result(self) -> c.Mapping[str, object]: |
| 77 |
task_ctx = TaskContext.current() |
| 78 |
|
| 79 |
try: |
| 80 |
return self._lazy_transform(task_ctx.latest_result) |
| 81 |
except NoRecordedResultError as ex: |
| 82 |
# RPFIX-5: UX: this causes multiple warnings/errors that need to be investigated, some likely from late addition of pre-task `when` projections |
| 83 |
# [WARNING]: An error occurred in a register expression: The _task.result property is unavailable: No task result has been recorded. |
| 84 |
# [WARNING]: An error occurred in a register expression: Error rendering expression: Type 'WarningSummary' is unsupported for variable storage. |
| 85 |
# - shell: echo {{ item }} |
| 86 |
# loop: [1,2,3] |
| 87 |
# failed_when: blar.rc != 0 |
| 88 |
# register: |
| 89 |
# blar: _task.result |
| 90 |
# |
| 91 |
# - debug: |
| 92 |
# var: blar |
| 93 |
# the template engine will turn this into an UndefinedMarker |
| 94 |
raise _attribute_unavailable.AttributeUnavailableError("The _task.result property is unavailable.") from ex |
| 95 |
|
| 96 |
@property |
| 97 |
def loop_result(self) -> c.Mapping[str, object]: |
| 98 |
task_ctx = TaskContext.current() |
| 99 |
|
| 100 |
try: |
| 101 |
# in-flight projections bypass the skipped conversions by setting finalize to False |
| 102 |
# RPFIX-5: IMPL: may need to fix Jinja's getattr/item AttributeError handling- if any code invoked beneath one of those raises AttributeError, Jinja |
| 103 |
# blindly creates a new UndefinedMarker with "CurrentTask has no attr loop_result" and loses the original AttributeError detail. Repro this by |
| 104 |
# tacking any bogus attr off the end of as_result_dict() here. |
| 105 |
return self._lazy_transform(task_ctx.build_loop_result(preview=True).as_result_dict()) |
| 106 |
except NotALoopError as ex: |
| 107 |
raise _attribute_unavailable.AttributeUnavailableError("The _task.loop_result property is unavailable.") from ex |
| 108 |
|
| 109 |
@property |
| 110 |
def polymorphic_result(self) -> c.Mapping[str, object]: |
| 111 |
task_ctx = TaskContext.current() |
| 112 |
|
| 113 |
if task_ctx.has_loop_exited: |
| 114 |
return self._lazy_transform(task_ctx.build_loop_result().as_result_dict()) |
| 115 |
|
| 116 |
try: |
| 117 |
return self._lazy_transform(task_ctx.latest_result) |
| 118 |
except NoRecordedResultError as ex: |
| 119 |
raise _attribute_unavailable.AttributeUnavailableError("The _task.polymorphic_result property is unavailable.") from ex |
| 120 |
|
| 121 |
|
| 122 |
@dataclasses.dataclass(kw_only=True, slots=True) |
| 123 |
class PendingChanges: |
| 124 |
"""Changes which will be applied when the action completes, including on failure.""" |
| 125 |
|
| 126 |
register_host_variables: dict[VariableLayer, dict[str, object]] = dataclasses.field(default_factory=dict) |
| 127 |
|
| 128 |
|
| 129 |
@dataclasses.dataclass(kw_only=True) |
| 130 |
class TaskContext(AmbientContextBase): |
| 131 |
"""Ambient context that wraps task execution on workers. It provides access to the currently executing task.""" |
| 132 |
|
| 133 |
@classmethod |
| 134 |
def create(cls, task: Task, task_vars: dict[str, t.Any], host_name: str) -> t.Self: |
| 135 |
task_vars.update(_task=CurrentTask()) |
| 136 |
|
| 137 |
return cls( |
| 138 |
_task=task, |
| 139 |
_base_task_vars=task_vars, |
| 140 |
_active_task_vars=task_vars, # starts out as a reference, but becomes a copy of _base_task_vars when starting a loop item |
| 141 |
_host_name=host_name, |
| 142 |
) |
| 143 |
|
| 144 |
def get_register_projections(self) -> dict[str, _engine.TemplateExpressionWrapper] | None: |
| 145 |
if not self._task.register: |
| 146 |
return None |
| 147 |
|
| 148 |
return {var_name: _engine.TemplateExpressionWrapper(expression=expression) for var_name, expression in self._task.register.items()} |
| 149 |
|
| 150 |
@functools.cached_property |
| 151 |
def inventory_rpc_client(self) -> _inventory_rpc.InventoryRPC: |
| 152 |
return _inventory_rpc.InventoryRPC.get_client() |
| 153 |
|
| 154 |
@property |
| 155 |
def host_name(self) -> str: |
| 156 |
return self._host_name |
| 157 |
|
| 158 |
@property |
| 159 |
def task(self) -> Task: |
| 160 |
return self._task |
| 161 |
|
| 162 |
@property |
| 163 |
def task_vars(self) -> dict[str, t.Any]: |
| 164 |
return self._active_task_vars |
| 165 |
|
| 166 |
@property |
| 167 |
def is_loop(self) -> bool: |
| 168 |
return self._loop_items is not None |
| 169 |
|
| 170 |
@property |
| 171 |
def has_loop_exited(self) -> bool: |
| 172 |
return self._has_loop_exited |
| 173 |
|
| 174 |
@property |
| 175 |
def current_item(self) -> object: |
| 176 |
return self._item |
| 177 |
|
| 178 |
@property |
| 179 |
def current_item_label(self) -> object: |
| 180 |
return self.task.loop_control.label or self.task_templar.variable_name_as_template(self._loop_var) |
| 181 |
|
| 182 |
_task: Task |
| 183 |
_base_task_vars: dict[str, t.Any] |
| 184 |
_active_task_vars: dict[str, t.Any] |
| 185 |
_host_name: str |
| 186 |
_registered_vars_enabled = False |
| 187 |
_raw_loop_results: list[UnifiedTaskResult] = dataclasses.field(default_factory=list) |
| 188 |
_loop_items: list[object] | None = None |
| 189 |
_has_loop_exited: bool = False |
| 190 |
_loop_var: str | None = None |
| 191 |
_item: object | None = None |
| 192 |
_item_index: int | None = None |
| 193 |
_index_var: str | None = None |
| 194 |
_loop_extended: dict[str, object] | None = None |
| 195 |
_templar: _engine.TemplateEngine | None = None |
| 196 |
_break_when_triggered: bool = False |
| 197 |
_inventory_rpc_client: _inventory_rpc.InventoryRPC | None = None |
| 198 |
_new_secrets: _secrets.NewSecretTracker = dataclasses.field(default_factory=_secrets._secret_masker.track_new_secrets) |
| 199 |
|
| 200 |
def flush_new_secrets(self) -> frozenset[str]: |
| 201 |
return self._new_secrets.flush() |
| 202 |
|
| 203 |
pending_changes: PendingChanges | None = None |
| 204 |
"""Pending changes which will be applied only if the current task succeeds.""" |
| 205 |
|
| 206 |
@contextlib.contextmanager |
| 207 |
def loop_item_context(self, te: TaskExecutor) -> t.Generator[None]: |
| 208 |
original_task = self.task |
| 209 |
original_play_context = te._play_context |
| 210 |
|
| 211 |
loop_item_task = self.task.copy(exclude_parent=True, exclude_tasks=True) |
| 212 |
loop_item_task._parent = self.task._parent |
| 213 |
loop_item_play_context = te._play_context.copy() |
| 214 |
|
| 215 |
self._task = loop_item_task |
| 216 |
te._play_context = loop_item_play_context |
| 217 |
|
| 218 |
try: |
| 219 |
yield |
| 220 |
finally: |
| 221 |
self._task = original_task |
| 222 |
te._play_context = original_play_context |
| 223 |
|
| 224 |
def start_loop(self) -> t.Generator[tuple[int, object]]: |
| 225 |
self._loop_var = loop_var = t.cast(str, self.task.loop_control.loop_var) |
| 226 |
self._index_var = index_var = t.cast(str, self.task.loop_control.index_var) |
| 227 |
|
| 228 |
extended = t.cast(bool, self.task.loop_control.extended) |
| 229 |
extended_allitems = t.cast(bool, self.task.loop_control.extended_allitems) |
| 230 |
|
| 231 |
items = self._loop_items |
| 232 |
items_len = len(items) |
| 233 |
|
| 234 |
for item_index, item in enumerate(self._loop_items): |
| 235 |
self._active_task_vars = self._base_task_vars.copy() # isolate changes to task vars between loop items |
| 236 |
self._templar = None # we're changing the values used to calculate the templar, null it out so the next requester re-creates it |
| 237 |
|
| 238 |
self._item = item |
| 239 |
self._item_index = item_index |
| 240 |
|
| 241 |
loop_vars: dict[str, object] = dict( |
| 242 |
ansible_loop_var=loop_var, |
| 243 |
) |
| 244 |
|
| 245 |
loop_vars[loop_var] = item |
| 246 |
|
| 247 |
if index_var: |
| 248 |
loop_vars['ansible_index_var'] = index_var |
| 249 |
loop_vars[index_var] = item_index |
| 250 |
|
| 251 |
if extended: |
| 252 |
ansible_loop: dict[str, object] = { |
| 253 |
'index': item_index + 1, |
| 254 |
'index0': item_index, |
| 255 |
'first': item_index == 0, |
| 256 |
'last': item_index + 1 == items_len, |
| 257 |
'length': items_len, |
| 258 |
'revindex': items_len - item_index, |
| 259 |
'revindex0': items_len - item_index - 1, |
| 260 |
} |
| 261 |
|
| 262 |
if extended_allitems: |
| 263 |
ansible_loop['allitems'] = items |
| 264 |
|
| 265 |
try: |
| 266 |
ansible_loop['nextitem'] = items[item_index + 1] |
| 267 |
except IndexError: |
| 268 |
pass |
| 269 |
|
| 270 |
if item_index - 1 >= 0: |
| 271 |
ansible_loop['previtem'] = items[item_index - 1] |
| 272 |
|
| 273 |
self._loop_extended = loop_vars['ansible_loop'] = ansible_loop |
| 274 |
|
| 275 |
self.task_vars.update(loop_vars) |
| 276 |
|
| 277 |
yield item_index, item |
| 278 |
|
| 279 |
if self._break_when_triggered: |
| 280 |
break |
| 281 |
|
| 282 |
self._has_loop_exited = True |
| 283 |
|
| 284 |
@property |
| 285 |
def task_templar(self) -> _engine.TemplateEngine: |
| 286 |
if not self._templar: |
| 287 |
self._templar = _engine.TemplateEngine(loader=self.task._loader, variables=self.task_vars) |
| 288 |
|
| 289 |
return self._templar |
| 290 |
|
| 291 |
@property |
| 292 |
def latest_result(self) -> c.MutableMapping[str, object]: |
| 293 |
if not self._raw_loop_results: |
| 294 |
raise NoRecordedResultError() |
| 295 |
|
| 296 |
return self._raw_loop_results[-1].as_result_dict() |
| 297 |
|
| 298 |
def _record_result(self, utr: UnifiedTaskResult) -> None: |
| 299 |
# CAUTION: This method can be called *before* start_loop when validation errors occur. |
| 300 |
# That results in various instance attributes not being set. |
| 301 |
# It also means that `self.task.loop_control` may have invalid values. |
| 302 |
|
| 303 |
self._enable_registered_vars() |
| 304 |
|
| 305 |
if isinstance(self.task.ignore_errors, bool): |
| 306 |
# HACK: avoid setting to True due to template failures -- this should go away once field attribute templating is fixed |
| 307 |
utr.ignore_errors = self.task.ignore_errors |
| 308 |
|
| 309 |
if isinstance(self.task.ignore_unreachable, bool): |
| 310 |
# HACK: avoid setting to True due to template failures -- this should go away once field attribute templating is fixed |
| 311 |
utr.ignore_unreachable = self.task.ignore_unreachable |
| 312 |
|
| 313 |
# _item_index will be None if start_loop was not called due to a field attribute error |
| 314 |
if not TaskContext.current().is_loop or self._item_index is None: |
| 315 |
self._raw_loop_results.clear() |
| 316 |
self._raw_loop_results.append(utr) |
| 317 |
|
| 318 |
return |
| 319 |
|
| 320 |
if TaskContext.current().has_loop_exited: |
| 321 |
return |
| 322 |
|
| 323 |
# now update the result with the item info, and append the result |
| 324 |
# to the list of results |
| 325 |
utr.loop_item = self._item |
| 326 |
utr.loop_var = self._loop_var |
| 327 |
utr.loop_extended = self._loop_extended |
| 328 |
|
| 329 |
if self._index_var: |
| 330 |
utr.loop_index = self._item_index |
| 331 |
utr.loop_index_var = self._index_var |
| 332 |
|
| 333 |
item_index = self._item_index |
| 334 |
result_count = len(self._raw_loop_results) |
| 335 |
|
| 336 |
if item_index == result_count: |
| 337 |
self._raw_loop_results.append(utr) # add new result |
| 338 |
elif item_index + 1 == result_count: |
| 339 |
self._raw_loop_results[item_index] = utr # replace existing result |
| 340 |
else: |
| 341 |
raise RuntimeError(f'Item index {item_index} does not match {result_count}.') |
| 342 |
|
| 343 |
self._populate_item_label(utr) |
| 344 |
|
| 345 |
def _populate_item_label(self, utr: UnifiedTaskResult) -> None: |
| 346 |
# gets templated here unlike rest of loop_control fields, depends on loop_var above |
| 347 |
item_label: object = ... |
| 348 |
|
| 349 |
if item_label_template := self.task.loop_control.label: |
| 350 |
try: |
| 351 |
item_label = self.task_templar.template(item_label_template) |
| 352 |
except AnsibleTemplateError as ex: |
| 353 |
display.error_as_warning('Failed to template loop_control label.', ex, obj=item_label_template) |
| 354 |
|
| 355 |
if item_label is ...: |
| 356 |
if self._loop_var is None: |
| 357 |
# _loop_var will be None if start_loop was not called due to a field attribute error (even if the error is for another field) |
| 358 |
item_label = '' |
| 359 |
else: |
| 360 |
item_label = self.task_templar.resolve_variable_expression(self._loop_var) |
| 361 |
|
| 362 |
utr.loop_item_label = item_label |
| 363 |
|
| 364 |
def build_loop_result(self, preview: bool = False) -> UnifiedTaskResult: |
| 365 |
if not self.is_loop: |
| 366 |
raise NotALoopError() |
| 367 |
|
| 368 |
if not preview and (self._item_index is None or len(self._raw_loop_results) not in (self._item_index, self._item_index + 1)): |
| 369 |
# RPFIX-9: FUTURE: can we ditch preview while retaining this safety check? |
| 370 |
# Loop results can be queried before or after loop results are recorded, so we need to accept a range of results. |
| 371 |
raise RuntimeError(f"Mismatch between item index {self._item_index} and loop result count {len(self._raw_loop_results)}.") |
| 372 |
|
| 373 |
# create the overall result item |
| 374 |
utr = UnifiedTaskResult.from_action_result_dict() |
| 375 |
utr.loop_results = self._raw_loop_results |
| 376 |
|
| 377 |
# RPFIX-5: IMPL: all the fields set in this loop could be converted to properties |
| 378 |
for item in self._raw_loop_results: |
| 379 |
if item.no_log: |
| 380 |
utr.no_log = True # ensure no_log processing recognizes at least one item needs to be censored |
| 381 |
|
| 382 |
utr._extend_warnings(item.warnings) |
| 383 |
utr._extend_deprecations(item.deprecations) |
| 384 |
|
| 385 |
if all(item.skipped for item in self._raw_loop_results): |
| 386 |
utr.set_skipped() |
| 387 |
utr.msg = 'All items skipped' |
| 388 |
elif utr.failed: |
| 389 |
utr.msg = 'One or more items failed' |
| 390 |
else: |
| 391 |
utr.msg = 'All items completed' |
| 392 |
|
| 393 |
return utr |
| 394 |
|
| 395 |
def update_task_vars(self, variables: dict[str, t.Any]) -> None: |
| 396 |
"""Update task variables for both the active task and, in the case of loops, subsequent tasks.""" |
| 397 |
for key, value in variables.items(): |
| 398 |
self._base_task_vars[key] = self._active_task_vars[key] = value |
| 399 |
|
| 400 |
def _enable_registered_vars(self) -> None: |
| 401 |
""" |
| 402 |
Inject registered variable expressions into task vars. |
| 403 |
This needs to be done one time after the action handler runs, or if a task results in no action running. |
| 404 |
Unlike other modifications to task vars, these changes will be persisted between loop items. |
| 405 |
""" |
| 406 |
if self._registered_vars_enabled: |
| 407 |
return |
| 408 |
|
| 409 |
if register_projections := self.get_register_projections(): |
| 410 |
self.update_task_vars(register_projections) |
| 411 |
|
| 412 |
self._registered_vars_enabled = True |
| 413 |
|
| 414 |
|
| 415 |
TaskArgsFinalizerCallback = t.Callable[[str, t.Any, _engine.TemplateEngine, t.Any], t.Any] |
| 416 |
"""Type alias for the shape of the `ActionBase.finalize_task_arg` method.""" |
| 417 |
|
| 418 |
|
| 419 |
class TaskArgsChainTemplar(ChainTemplar): |
| 420 |
""" |
| 421 |
A ChainTemplar that carries a user-provided context object, optionally provided by `ActionBase.get_finalize_task_args_context`. |
| 422 |
TaskArgsFinalizer provides the context to each `ActionBase.finalize_task_arg` call to allow for more complex/stateful customization. |
| 423 |
""" |
| 424 |
|
| 425 |
def __init__(self, *sources: c.Mapping, templar: _engine.TemplateEngine, callback: TaskArgsFinalizerCallback, context: t.Any) -> None: |
| 426 |
super().__init__(*sources, templar=templar) |
| 427 |
|
| 428 |
self.callback = callback |
| 429 |
self.context = context |
| 430 |
|
| 431 |
def template(self, key: t.Any, value: t.Any) -> t.Any: |
| 432 |
return self.callback(key, value, self.templar, self.context) |
| 433 |
|
| 434 |
|
| 435 |
class TaskArgsFinalizer: |
| 436 |
"""Invoked during task args finalization; allows actions to override default arg processing (e.g., templating).""" |
| 437 |
|
| 438 |
def __init__(self, *args: c.Mapping[str, t.Any] | str | None, templar: _engine.TemplateEngine) -> None: |
| 439 |
self._args_layers = [arg for arg in args if arg is not None] |
| 440 |
self._templar = templar |
| 441 |
|
| 442 |
def finalize(self, callback: TaskArgsFinalizerCallback, context: t.Any) -> dict[str, t.Any]: |
| 443 |
from ansible import constants |
| 444 |
|
| 445 |
resolved_layers: list[c.Mapping[str, t.Any]] = [] |
| 446 |
|
| 447 |
for layer in self._args_layers: |
| 448 |
if isinstance(layer, (str, _vault.EncryptedString)): # EncryptedString can hide a template |
| 449 |
if constants.config.get_config_value('INJECT_FACTS_AS_VARS'): |
| 450 |
display.warning( |
| 451 |
"Using a template for task args is unsafe in some situations " |
| 452 |
"(see https://docs.ansible.com/ansible/devel/reference_appendices/faq.html#argsplat-unsafe).", |
| 453 |
obj=layer, |
| 454 |
) |
| 455 |
|
| 456 |
resolved_layer = self._templar.resolve_to_container(layer, options=_engine.TemplateOptions(value_for_omit={})) |
| 457 |
else: |
| 458 |
resolved_layer = layer |
| 459 |
|
| 460 |
if not isinstance(resolved_layer, dict): |
| 461 |
raise AnsibleError(f'Task args must resolve to a {native_type_name(dict)!r} not {native_type_name(resolved_layer)!r}.', obj=layer) |
| 462 |
|
| 463 |
resolved_layers.append(resolved_layer) |
| 464 |
|
| 465 |
ct = TaskArgsChainTemplar(*reversed(resolved_layers), templar=self._templar, callback=callback, context=context) |
| 466 |
|
| 467 |
return ct.as_dict() |
| 468 |
|
| 469 |
|
| 470 |
class Source(enum.Enum): |
| 471 |
ACTION = enum.auto() |
| 472 |
ANY = enum.auto() |
| 473 |
|
| 474 |
|
| 475 |
class Destination(enum.Enum): |
| 476 |
CALLBACK = enum.auto() |
| 477 |
NOT_CALLBACK = enum.auto() |
| 478 |
ANY = enum.auto() |
| 479 |
|
| 480 |
|
| 481 |
@dataclasses.dataclass(kw_only=True, frozen=True, slots=True) |
| 482 |
class FieldSettings: |
| 483 |
key: str | None = None |
| 484 |
source: Source | None = None |
| 485 |
destination: Destination | None = None |
| 486 |
conversion_func: t.Callable[[object], object] | None = None |
| 487 |
|
| 488 |
|
| 489 |
_type = type |
| 490 |
|
| 491 |
|
| 492 |
@dataclasses.dataclass(kw_only=True, frozen=True, slots=True) |
| 493 |
class ResolvedField: |
| 494 |
name: str |
| 495 |
type: type |
| 496 |
optional: bool |
| 497 |
field: dataclasses.Field | None |
| 498 |
metadata: FieldSettings |
| 499 |
|
| 500 |
@classmethod |
| 501 |
def from_field(cls, type_hints: dict[str, t.Any], metadata: FieldSettings, dc_field: dataclasses.Field) -> t.Self: |
| 502 |
resolved_type = type_hints[dc_field.name] |
| 503 |
|
| 504 |
if isinstance(resolved_type, types.UnionType): |
| 505 |
args = resolved_type.__args__ |
| 506 |
|
| 507 |
if len(args) == 2 and args[0] is types.NoneType: |
| 508 |
resolved_type = args[1] |
| 509 |
optional = True |
| 510 |
elif len(args) == 2 and args[1] is types.NoneType: |
| 511 |
resolved_type = args[0] |
| 512 |
optional = True |
| 513 |
else: |
| 514 |
raise NotImplementedError(f"Unexpected union type args: {args}") |
| 515 |
else: |
| 516 |
optional = False |
| 517 |
|
| 518 |
if isinstance(resolved_type, types.GenericAlias): |
| 519 |
resolved_type = t.get_origin(resolved_type) |
| 520 |
elif (orig_bases := types.get_original_bases(resolved_type)) and orig_bases[0] is t.TypedDict: |
| 521 |
resolved_type = dict |
| 522 |
|
| 523 |
return cls( |
| 524 |
name=dc_field.name, |
| 525 |
type=resolved_type, |
| 526 |
optional=optional, |
| 527 |
field=dc_field, |
| 528 |
metadata=metadata, |
| 529 |
) |
| 530 |
|
| 531 |
@property |
| 532 |
def result_key(self) -> str: |
| 533 |
return self.metadata.key or self.name |
| 534 |
|
| 535 |
|
| 536 |
def export_only( |
| 537 |
key: str | None = None, |
| 538 |
*, |
| 539 |
destination: Destination = Destination.ANY, |
| 540 |
conversion_func: t.Callable[[object], object] | None = None, |
| 541 |
) -> dict[str, t.Any]: |
| 542 |
return field( |
| 543 |
key, |
| 544 |
source=None, |
| 545 |
destination=destination, |
| 546 |
conversion_func=conversion_func, |
| 547 |
) |
| 548 |
|
| 549 |
|
| 550 |
def import_export( |
| 551 |
key: str | None = None, |
| 552 |
*, |
| 553 |
source: Source = Source.ANY, |
| 554 |
destination: Destination = Destination.ANY, |
| 555 |
conversion_func: t.Callable[[object], object] | None = None, |
| 556 |
) -> dict[str, t.Any]: |
| 557 |
return field( |
| 558 |
key, |
| 559 |
source=source, |
| 560 |
destination=destination, |
| 561 |
conversion_func=conversion_func, |
| 562 |
) |
| 563 |
|
| 564 |
|
| 565 |
def field( |
| 566 |
key: str | None = None, |
| 567 |
*, |
| 568 |
source: Source | None = None, |
| 569 |
destination: Destination | None = None, |
| 570 |
conversion_func: t.Callable[[object], object] | None = None, |
| 571 |
) -> dict[str, t.Any]: |
| 572 |
return dict( |
| 573 |
ansible=FieldSettings( |
| 574 |
key=key, |
| 575 |
source=source, |
| 576 |
destination=destination, |
| 577 |
conversion_func=conversion_func, |
| 578 |
) |
| 579 |
) |
| 580 |
|
| 581 |
|
| 582 |
_DEFAULT_FIELD_SETTINGS = FieldSettings() |
| 583 |
|
| 584 |
|
| 585 |
def _convert_no_log(value: object) -> bool: |
| 586 |
if not isinstance(value, bool): |
| 587 |
# RPFIX-5: UX: do we want to keep any kind of custom warning regarding this value always being True when not a bool? |
| 588 |
# display.warning(f'Invalid _ansible_no_log value of type {type(value).__name__!r} in task result, output will be masked.') |
| 589 |
value = True |
| 590 |
|
| 591 |
return value |
| 592 |
|
| 593 |
|
| 594 |
@dataclasses.dataclass(kw_only=True, frozen=True, slots=True) |
| 595 |
class AddHost: |
| 596 |
host_name: str |
| 597 |
host_vars: dict[str, object] | None = None |
| 598 |
parent_group_names: list[str] | None = None |
| 599 |
|
| 600 |
def __post_init__(self): ... |
| 601 |
|
| 602 |
@classmethod |
| 603 |
def from_dict(cls, value: object) -> AddHost | None: |
| 604 |
if isinstance(value, dict): |
| 605 |
if groups := value.pop('groups'): |
| 606 |
value['parent_group_names'] = groups |
| 607 |
|
| 608 |
try: |
| 609 |
return cls(**value) |
| 610 |
except Exception as ex: |
| 611 |
display.error_as_warning('Ignoring invalid add_host value in task result.', exception=ex) |
| 612 |
|
| 613 |
return None |
| 614 |
|
| 615 |
|
| 616 |
_dataclass_validation.inject_post_init_validation(AddHost, allow_subclasses=True) |
| 617 |
|
| 618 |
|
| 619 |
@dataclasses.dataclass(kw_only=True, frozen=True, slots=True) |
| 620 |
class AddGroup: |
| 621 |
group_name: str |
| 622 |
parent_group_names: list[str] |
| 623 |
|
| 624 |
def __post_init__(self): ... |
| 625 |
|
| 626 |
|
| 627 |
_dataclass_validation.inject_post_init_validation(AddGroup, allow_subclasses=True) |
| 628 |
|
| 629 |
|
| 630 |
class StatsDict(t.TypedDict): |
| 631 |
data: dict[str, object] |
| 632 |
per_host: t.NotRequired[object | None] # really bool, but no validation |
| 633 |
aggregate: t.NotRequired[object | None] # really bool, but no validation |
| 634 |
|
| 635 |
|
| 636 |
def _convert_stats(value: t.Any) -> StatsDict | None: |
| 637 |
if not isinstance(value, dict) or not isinstance(value.get('data'), dict): |
| 638 |
display.warning('Ignoring invalid ansible_stats value in task result.') |
| 639 |
value = None |
| 640 |
|
| 641 |
return value |
| 642 |
|
| 643 |
|
| 644 |
def _convert_warnings(value: object) -> list[_messages.WarningSummary] | None: |
| 645 |
if not value: |
| 646 |
return None |
| 647 |
|
| 648 |
if not isinstance(value, list): |
| 649 |
display.warning(f"Task result `warnings` was {native_type_name(value)} instead of {native_type_name(list)} and has been discarded.") |
| 650 |
return None |
| 651 |
|
| 652 |
warnings: list[_messages.WarningSummary] = [] |
| 653 |
|
| 654 |
for warning in value: |
| 655 |
if not isinstance(warning, _messages.WarningSummary): |
| 656 |
# translate non-WarningMessageDetail messages |
| 657 |
warning = _messages.WarningSummary( |
| 658 |
event=_messages.Event( |
| 659 |
msg=str(warning), |
| 660 |
), |
| 661 |
) |
| 662 |
|
| 663 |
if warning_ctx := _display_utils.DeferredWarningContext.current(optional=True): |
| 664 |
warning_ctx.capture(warning) |
| 665 |
else: |
| 666 |
warnings.append(warning) |
| 667 |
|
| 668 |
return warnings |
| 669 |
|
| 670 |
|
| 671 |
def _convert_deprecations(value: object) -> list[_messages.DeprecationSummary] | None: |
| 672 |
if not value: |
| 673 |
return None |
| 674 |
|
| 675 |
if not isinstance(value, list): |
| 676 |
display.warning(f"Task result `deprecations` was {native_type_name(value)} instead of {native_type_name(list)} and has been discarded.") |
| 677 |
return None |
| 678 |
|
| 679 |
deprecations: list[_messages.DeprecationSummary] = [] |
| 680 |
|
| 681 |
for deprecation in value: |
| 682 |
if not isinstance(deprecation, _messages.DeprecationSummary): |
| 683 |
# translate non-DeprecationSummary message dicts |
| 684 |
try: |
| 685 |
if (collection_name := deprecation.pop('collection_name', ...)) is not ...: |
| 686 |
# deprecated: description='enable the deprecation message for collection_name' core_version='2.23' |
| 687 |
# CAUTION: This deprecation cannot be enabled until the replacement (deprecator) has been documented, and the schema finalized. |
| 688 |
# self.deprecated('The `collection_name` key in the `deprecations` dictionary is deprecated.', version='2.27') |
| 689 |
deprecation.update(deprecator=deprecator_from_collection_name(collection_name)) |
| 690 |
|
| 691 |
deprecation = _messages.DeprecationSummary( |
| 692 |
event=_messages.Event( |
| 693 |
msg=deprecation.pop('msg'), |
| 694 |
), |
| 695 |
**deprecation, |
| 696 |
) |
| 697 |
except Exception as ex: |
| 698 |
display.error_as_warning("Task result `deprecations` contained an invalid item.", exception=ex) |
| 699 |
|
| 700 |
if warning_ctx := _display_utils.DeferredWarningContext.current(optional=True): |
| 701 |
warning_ctx.capture(deprecation) |
| 702 |
else: |
| 703 |
deprecations.append(deprecation) |
| 704 |
|
| 705 |
return deprecations |
| 706 |
|
| 707 |
|
| 708 |
DROP_AND_WARN = ResolvedField(name='__drop__', type=str, optional=True, field=None, metadata=FieldSettings()) |
| 709 |
|
| 710 |
|
| 711 |
class VariableLayer(enum.IntEnum): |
| 712 |
""" |
| 713 |
Variable layer at which variables are registered. |
| 714 |
|
| 715 |
CAUTION: This enum is exposed as public API in ActionBase. |
| 716 |
""" |
| 717 |
|
| 718 |
# IMPORTANT: The order of these enum values determines the order in which they will be applied to variable manager. |
| 719 |
# This matters for precedence of layers for which variable manager does not independently track. |
| 720 |
|
| 721 |
CACHEABLE_FACT = enum.auto() |
| 722 |
INCLUDE_VARS = enum.auto() |
| 723 |
EPHEMERAL_FACT = enum.auto() |
| 724 |
REGISTER_VARS = enum.auto() |
| 725 |
|
| 726 |
|
| 727 |
@dataclasses.dataclass(kw_only=True, slots=True) |
| 728 |
class UnifiedTaskResult: |
| 729 |
_changed: bool | None = dataclasses.field(default=None, metadata=import_export("changed")) |
| 730 |
|
| 731 |
@property |
| 732 |
def changed(self) -> bool: |
| 733 |
if self._changed is not None or self.loop_results is None: |
| 734 |
return bool(self._changed) |
| 735 |
|
| 736 |
return any(loop_result.changed for loop_result in self.loop_results) |
| 737 |
|
| 738 |
@changed.setter |
| 739 |
def changed(self, value: bool) -> None: |
| 740 |
self._changed = value |
| 741 |
|
| 742 |
_failed: bool | None = dataclasses.field(default=None, metadata=import_export("failed", destination=Destination.NOT_CALLBACK)) |
| 743 |
|
| 744 |
@property |
| 745 |
def failed(self) -> bool: |
| 746 |
if self._failed is None and self.rc is not None and self.rc != 0: |
| 747 |
return True |
| 748 |
|
| 749 |
if self.failed_when_result is not None: |
| 750 |
return bool(self.failed_when_result) |
| 751 |
|
| 752 |
if self.loop_results and any(loop_result.failed_when_result is not None for loop_result in self.loop_results): |
| 753 |
return any(loop_result.failed_when_result for loop_result in self.loop_results) |
| 754 |
|
| 755 |
if self._failed is not None or self.loop_results is None: |
| 756 |
return bool(self._failed) |
| 757 |
|
| 758 |
return any(loop_result.failed for loop_result in self.loop_results) |
| 759 |
|
| 760 |
@failed.setter |
| 761 |
def failed(self, value: bool) -> None: |
| 762 |
self._failed = value |
| 763 |
|
| 764 |
_unreachable: bool | None = dataclasses.field(default=None, metadata=import_export("unreachable")) |
| 765 |
|
| 766 |
@property |
| 767 |
def unreachable(self) -> bool | None: |
| 768 |
if self._unreachable is not None or self.loop_results is None: |
| 769 |
result = bool(self._unreachable) |
| 770 |
else: |
| 771 |
result = any(loop_result.unreachable for loop_result in self.loop_results) |
| 772 |
|
| 773 |
return result or None |
| 774 |
|
| 775 |
@unreachable.setter |
| 776 |
def unreachable(self, value: bool) -> None: |
| 777 |
self._unreachable = value |
| 778 |
|
| 779 |
_skipped: bool | None = dataclasses.field(default=None, metadata=import_export("skipped", destination=Destination.NOT_CALLBACK)) |
| 780 |
|
| 781 |
@property |
| 782 |
def skipped(self) -> bool | None: |
| 783 |
if self._skipped is not None or self.loop_results is None: |
| 784 |
result = bool(self._skipped) |
| 785 |
else: |
| 786 |
# Loop tasks are only considered skipped if all items were skipped. |
| 787 |
result = all(loop_result.skipped for loop_result in self.loop_results) |
| 788 |
|
| 789 |
return result or None |
| 790 |
|
| 791 |
@skipped.setter |
| 792 |
def skipped(self, value: bool) -> None: |
| 793 |
self._skipped = value |
| 794 |
|
| 795 |
_ignore_errors: bool = False # formerly _ansible_ignore_errors |
| 796 |
|
| 797 |
@property |
| 798 |
def ignore_errors(self) -> bool: |
| 799 |
return self._ignore_errors if self.loop_results is None else any(loop_result._ignore_errors for loop_result in self.loop_results) |
| 800 |
|
| 801 |
@ignore_errors.setter |
| 802 |
def ignore_errors(self, value: bool) -> None: |
| 803 |
self._ignore_errors = value |
| 804 |
|
| 805 |
_ignore_unreachable: bool = False # formerly _ansible_ignore_unreachable |
| 806 |
|
| 807 |
@property |
| 808 |
def ignore_unreachable(self) -> bool: |
| 809 |
return self._ignore_unreachable if self.loop_results is None else any(loop_result._ignore_unreachable for loop_result in self.loop_results) |
| 810 |
|
| 811 |
@ignore_unreachable.setter |
| 812 |
def ignore_unreachable(self, value: bool) -> None: |
| 813 |
self._ignore_unreachable = value |
| 814 |
|
| 815 |
_warnings: list[_messages.WarningSummary] | None = dataclasses.field( |
| 816 |
default=None, |
| 817 |
metadata=import_export("warnings", conversion_func=_convert_warnings), |
| 818 |
) |
| 819 |
|
| 820 |
@property |
| 821 |
def warnings(self) -> list[_messages.WarningSummary] | None: |
| 822 |
if (current_warnings := self._warnings) is None and (warning_ctx := _display_utils.DeferredWarningContext.current(optional=True)): |
| 823 |
current_warnings = warning_ctx.get_warnings() |
| 824 |
|
| 825 |
return current_warnings |
| 826 |
|
| 827 |
_deprecations: list[_messages.DeprecationSummary] | None = dataclasses.field( |
| 828 |
default=None, |
| 829 |
metadata=import_export("deprecations", conversion_func=_convert_deprecations), |
| 830 |
) |
| 831 |
|
| 832 |
@property |
| 833 |
def deprecations(self) -> list[_messages.DeprecationSummary] | None: |
| 834 |
if (current_deprecations := self._deprecations) is None and (warning_ctx := _display_utils.DeferredWarningContext.current(optional=True)): |
| 835 |
current_deprecations = warning_ctx.get_deprecation_warnings() |
| 836 |
|
| 837 |
return current_deprecations |
| 838 |
|
| 839 |
ansible_facts: dict[str, t.Any] | None = dataclasses.field(default=None, metadata=import_export()) |
| 840 |
async_result: dict[str, t.Any] | None = dataclasses.field(default=None, metadata=export_only()) |
| 841 |
ansible_parsed: bool | None = dataclasses.field(default=None, metadata=import_export(destination=Destination.NOT_CALLBACK)) # formerly _ansible_parsed |
| 842 |
exception: _messages.ErrorSummary | None = dataclasses.field(default=None, metadata=import_export()) |
| 843 |
finished: bool | None = dataclasses.field(default=None, metadata=import_export()) |
| 844 |
msg: object | None = dataclasses.field(default=None, metadata=import_export()) |
| 845 |
no_log: bool | None = dataclasses.field( |
| 846 |
default=None, metadata=import_export("_ansible_no_log", conversion_func=_convert_no_log, source=Source.ACTION, destination=Destination.CALLBACK) |
| 847 |
) |
| 848 |
verbose_always: bool | None = dataclasses.field( |
| 849 |
default=None, metadata=import_export("_ansible_verbose_always", source=Source.ACTION, destination=Destination.CALLBACK) |
| 850 |
) |
| 851 |
verbose_override: bool | None = dataclasses.field( |
| 852 |
default=None, metadata=import_export("_ansible_verbose_override", source=Source.ACTION, destination=Destination.CALLBACK) |
| 853 |
) |
| 854 |
rc: int | None = dataclasses.field(default=None, metadata=import_export()) |
| 855 |
suppress_tmpdir_delete: bool | None = dataclasses.field(default=None, metadata=field("_ansible_suppress_tmpdir_delete", source=Source.ANY)) |
| 856 |
module_stderr: str | None = dataclasses.field(default=None, metadata=export_only()) |
| 857 |
module_stdout: str | None = dataclasses.field(default=None, metadata=export_only()) |
| 858 |
result_data: dict[str, object] = dataclasses.field(default_factory=dict) |
| 859 |
is_module: bool |
| 860 |
attempts: int | None = dataclasses.field(default=None, metadata=export_only()) |
| 861 |
retries: int | None = dataclasses.field(default=None, metadata=export_only()) |
| 862 |
notify: list[str] = dataclasses.field(default_factory=list) |
| 863 |
delegated_host: str | None = None |
| 864 |
callback_delegated_vars_subset: dict[str, object] | None = dataclasses.field( |
| 865 |
default=None, metadata=export_only("_ansible_delegated_vars", destination=Destination.CALLBACK) |
| 866 |
) |
| 867 |
diff: object | None = dataclasses.field(default=None, metadata=import_export()) # RPFIX-9: FUTURE: validation with custom conversion func |
| 868 |
pending_changes: PendingChanges = dataclasses.field(default_factory=PendingChanges) |
| 869 |
"""Changes which will be applied when the action completes, including on failure.""" |
| 870 |
stats: StatsDict | None = dataclasses.field(default=None, metadata=import_export('ansible_stats', conversion_func=_convert_stats)) |
| 871 |
async_job_id: str | None = dataclasses.field(default=None, metadata=import_export('ansible_job_id')) |
| 872 |
include_file: str | None = None |
| 873 |
include_args: dict[str, object] | None = None # RPFIX-9: FUTURE: make this a dataclass |
| 874 |
registered_values: c.Mapping[str, object] | None = None |
| 875 |
"""Values to register unconditionally, including on failure or when skipped.""" |
| 876 |
|
| 877 |
skip_reason: str | None = dataclasses.field(default=None, metadata=export_only()) |
| 878 |
skipped_reason: str | None = dataclasses.field(default=None, metadata=export_only()) |
| 879 |
"""The `skipped_reason` field is deprecated. Use `skip_reason` instead.""" |
| 880 |
|
| 881 |
false_condition: object | None = dataclasses.field(default=None, metadata=export_only()) |
| 882 |
|
| 883 |
changed_when_result: object | None = dataclasses.field(default=None, metadata=export_only()) # RPFIX-9: FUTURE: `bool | str` once validator supports that |
| 884 |
failed_when_result: object | None = dataclasses.field(default=None, metadata=export_only()) # RPFIX-9: FUTURE: `bool | str` once validator supports that |
| 885 |
break_when_result: object | None = dataclasses.field(default=None, metadata=export_only()) # RPFIX-9: FUTURE: `bool | str` once validator supports that |
| 886 |
|
| 887 |
changed_when_suppressed_exception: _messages.ErrorSummary | None = dataclasses.field(default=None, metadata=export_only()) |
| 888 |
failed_when_suppressed_exception: _messages.ErrorSummary | None = dataclasses.field(default=None, metadata=export_only()) |
| 889 |
break_when_suppressed_exception: _messages.ErrorSummary | None = dataclasses.field(default=None, metadata=export_only()) |
| 890 |
|
| 891 |
loop_var: str | None = dataclasses.field(default=None, metadata=export_only('ansible_loop_var')) |
| 892 |
loop_index_var: str | None = dataclasses.field(default=None, metadata=export_only('ansible_index_var')) |
| 893 |
loop_item_label: object | None = dataclasses.field(default=None, metadata=export_only('_ansible_item_label', destination=Destination.CALLBACK)) |
| 894 |
loop_item: object | None = dataclasses.field(default=None, metadata=export_only()) # exported as self.loop_var value |
| 895 |
loop_index: object | None = dataclasses.field(default=None, metadata=export_only()) # exported as self.loop_index_var value |
| 896 |
loop_extended: dict[str, object] | None = dataclasses.field(default=None, metadata=export_only('ansible_loop')) |
| 897 |
loop_results: list[t.Self] | None = None |
| 898 |
|
| 899 |
@classmethod |
| 900 |
@functools.cache |
| 901 |
def get_result_key_to_resolved_field_mapping(cls, source_is_module: bool) -> dict[str, ResolvedField]: |
| 902 |
mapping = {} |
| 903 |
type_hints = t.get_type_hints(cls) |
| 904 |
|
| 905 |
for dc_field in dataclasses.fields(cls): |
| 906 |
metadata = t.cast(FieldSettings, dc_field.metadata.get('ansible', _DEFAULT_FIELD_SETTINGS)) |
| 907 |
resolved_field = ResolvedField.from_field(type_hints, metadata, dc_field) |
| 908 |
|
| 909 |
if metadata.source is Source.ACTION and source_is_module: |
| 910 |
mapping[resolved_field.result_key] = DROP_AND_WARN |
| 911 |
elif metadata.source is Source.ACTION or metadata.source is Source.ANY: |
| 912 |
mapping[resolved_field.result_key] = resolved_field |
| 913 |
|
| 914 |
return mapping |
| 915 |
|
| 916 |
@classmethod |
| 917 |
@functools.cache |
| 918 |
def _get_field_name_to_result_key_mapping(cls, *, for_callback: bool, for_round_trip: bool) -> dict[str, str]: |
| 919 |
mapping = {} |
| 920 |
|
| 921 |
for dc_field in dataclasses.fields(cls): |
| 922 |
metadata = t.cast(FieldSettings, dc_field.metadata.get('ansible', _DEFAULT_FIELD_SETTINGS)) |
| 923 |
|
| 924 |
if ( |
| 925 |
metadata.destination is Destination.ANY |
| 926 |
or ((for_round_trip or for_callback) and metadata.destination is Destination.CALLBACK) |
| 927 |
or ((for_round_trip or not for_callback) and metadata.destination is Destination.NOT_CALLBACK) |
| 928 |
): |
| 929 |
key = metadata.key or dc_field.name |
| 930 |
field_name = key if hasattr(cls, key) else dc_field.name # properties matching the exported key take precedence over the field during export |
| 931 |
|
| 932 |
mapping[field_name] = key |
| 933 |
|
| 934 |
return mapping |
| 935 |
|
| 936 |
@classmethod |
| 937 |
def from_action_result_dict(cls, result: dict[str, object] | None = None) -> t.Self: |
| 938 |
return cls._from_result_dict(result or {}, source_is_module=False) |
| 939 |
|
| 940 |
@classmethod |
| 941 |
def _from_result_dict(cls, result: dict[str, object], source_is_module: bool) -> t.Self: |
| 942 |
if not isinstance(result, dict): |
| 943 |
raise TypeError(f'Malformed result. Received {type(result)} instead of {dict}.') |
| 944 |
|
| 945 |
if source_is_module and (new_secrets := result.pop('_ansible_new_secrets', None)): |
| 946 |
register_secrets([to_text(s) for s in new_secrets]) |
| 947 |
|
| 948 |
fields = cls.get_result_key_to_resolved_field_mapping(source_is_module=source_is_module) |
| 949 |
result_data: dict[str, object] = {} |
| 950 |
kwargs: dict[str, t.Any] = dict( |
| 951 |
result_data=result_data, |
| 952 |
) |
| 953 |
|
| 954 |
for key, value in result.items(): |
| 955 |
if resolved_field := fields.get(key): |
| 956 |
# deprecated: description='uncomment to enable user-facing warnings for modules/actions returning skipped' core_version='2.23' |
| 957 |
# if key == 'skipped': |
| 958 |
# display.deprecated( |
| 959 |
# msg="Returning 'skipped' from a module or action plugin is deprecated.", |
| 960 |
# version="2.25", |
| 961 |
# ) |
| 962 |
if resolved_field is DROP_AND_WARN: |
| 963 |
display.warning(f"Removed reserved key {key!r} from module result.", obj=value) |
| 964 |
else: |
| 965 |
kwargs[resolved_field.name] = cls.convert_field(resolved_field, value) |
| 966 |
elif source_is_module and key.startswith('_ansible_'): |
| 967 |
display.warning(f"Removed reserved key {key!r} from module result.", obj=value) |
| 968 |
else: |
| 969 |
result_data[key] = value |
| 970 |
|
| 971 |
return cls(is_module=source_is_module, **kwargs) |
| 972 |
|
| 973 |
def _result_key_magic(self, key: str) -> str: |
| 974 |
match key: |
| 975 |
case "loop_item": |
| 976 |
return self.loop_var or 'item' # RPFIX-9: FUTURE: centralize the default logic |
| 977 |
|
| 978 |
case "loop_index": |
| 979 |
return self.loop_index_var |
| 980 |
|
| 981 |
case _: |
| 982 |
return key |
| 983 |
|
| 984 |
def as_result_dict( |
| 985 |
self, |
| 986 |
*, |
| 987 |
for_callback: bool = False, |
| 988 |
for_round_trip: bool = False, |
| 989 |
censor_callback_result: bool = False, |
| 990 |
mask_callback_result: bool = False, |
| 991 |
) -> dict[str, object]: |
| 992 |
result: dict[str, t.Any] = { |
| 993 |
self._result_key_magic(result_key): value |
| 994 |
for field_name, result_key in self._get_field_name_to_result_key_mapping(for_callback=for_callback, for_round_trip=for_round_trip).items() |
| 995 |
if (value := getattr(self, field_name)) is not None |
| 996 |
} |
| 997 |
|
| 998 |
result.update(self.result_data) |
| 999 |
|
| 1000 |
# RPFIX-5: IMPL: is this where we want stdout/stderr handling? |
| 1001 |
# pre-split stdout/stderr into lines if needed |
| 1002 |
|
| 1003 |
if 'stdout' in result and 'stdout_lines' not in result: |
| 1004 |
# if the value is 'False', a default won't catch it. |
| 1005 |
txt = result.get('stdout', None) or '' |
| 1006 |
result.update(stdout_lines=txt.splitlines()) |
| 1007 |
|
| 1008 |
if 'stderr' in result and 'stderr_lines' not in result: |
| 1009 |
# if the value is 'False', a default won't catch it. |
| 1010 |
txt = result.get('stderr', None) or '' |
| 1011 |
result.update(stderr_lines=txt.splitlines()) |
| 1012 |
|
| 1013 |
if for_callback: |
| 1014 |
if censor_callback_result: |
| 1015 |
result = {key: value for key in PRESERVE if (value := result.get(key, ...)) is not ...} |
| 1016 |
result.update(censored="the output has been hidden due to the fact that 'no_log: true' was specified for this result") |
| 1017 |
|
| 1018 |
if self.loop_results is not None: |
| 1019 |
# loop results need to be added after censor_result on the outer result since it's currently naive about whether it's looking at a loop item or not |
| 1020 |
result.update( |
| 1021 |
results=[ |
| 1022 |
loop_result.as_result_dict( |
| 1023 |
for_callback=for_callback, |
| 1024 |
for_round_trip=for_round_trip, |
| 1025 |
censor_callback_result=censor_callback_result or loop_result.no_log, |
| 1026 |
mask_callback_result=mask_callback_result, |
| 1027 |
) |
| 1028 |
for loop_result in self.loop_results |
| 1029 |
] |
| 1030 |
) |
| 1031 |
|
| 1032 |
if for_callback: |
| 1033 |
result = _vars._transform_to_native_types_for_callback(result, mask_values=mask_callback_result) |
| 1034 |
|
| 1035 |
return result |
| 1036 |
|
| 1037 |
def finalize_registered_values(self) -> None: |
| 1038 |
task_ctx = TaskContext.current() |
| 1039 |
|
| 1040 |
if not (register_projections := task_ctx.get_register_projections()): |
| 1041 |
return |
| 1042 |
|
| 1043 |
registered_values = {} |
| 1044 |
registered_errors = [] |
| 1045 |
|
| 1046 |
for var_name, expression in register_projections.items(): |
| 1047 |
try: |
| 1048 |
registered_values[var_name] = task_ctx.task_templar.template(expression) |
| 1049 |
except Exception as ex: |
| 1050 |
event = _error_factory.ControllerEventFactory.from_exception(ex, False) |
| 1051 |
event_message = _event_utils.format_event_brief_message(event) |
| 1052 |
undef_message = f"The variable {var_name!r} is undefined because its register expression failed: {event_message}" |
| 1053 |
undef_value = trust_as_template(f"{{{{ undef({undef_message!r}) }}}}") |
| 1054 |
|
| 1055 |
if expression_origin := _tags.Origin.get_tag(expression.expression): |
| 1056 |
undef_value = expression_origin.tag(undef_value) |
| 1057 |
|
| 1058 |
registered_values[var_name] = undef_value |
| 1059 |
|
| 1060 |
try: |
| 1061 |
raise Exception(f"Register projection {var_name!r} failed.") from ex |
| 1062 |
except Exception as ex: |
| 1063 |
registered_errors.append(ex) |
| 1064 |
|
| 1065 |
# RPFIX-9: FUTURE: merge registered_values into the pending VariableLayer.REGISTER_VARS layer instead of having a separate field |
| 1066 |
self.registered_values = registered_values |
| 1067 |
|
| 1068 |
if not registered_errors: |
| 1069 |
return |
| 1070 |
|
| 1071 |
chain = ( |
| 1072 |
_messages.EventChain( |
| 1073 |
msg_reason="The original task error before register failed was:", |
| 1074 |
traceback_reason="The above exception occurred before the following exception:", |
| 1075 |
event=self.exception.event, |
| 1076 |
) |
| 1077 |
if self.exception |
| 1078 |
else None |
| 1079 |
) |
| 1080 |
|
| 1081 |
try: |
| 1082 |
raise ExceptionGroup( |
| 1083 |
f"Task failed due to errors in {len(registered_errors)} out of {len(register_projections)} register projections.", |
| 1084 |
registered_errors, |
| 1085 |
) |
| 1086 |
except ExceptionGroup as ex: |
| 1087 |
event = _error_factory.ControllerEventFactory.from_exception(ex, _traceback.is_traceback_enabled(_traceback.TracebackEvent.ERROR)) |
| 1088 |
event = dataclasses.replace(event, chain=chain) |
| 1089 |
|
| 1090 |
self.failed = True |
| 1091 |
self.exception = _messages.ErrorSummary( |
| 1092 |
event=event, |
| 1093 |
) |
| 1094 |
|
| 1095 |
def _extend_warnings(self, warnings: c.Iterable[_messages.WarningSummary] | None) -> None: |
| 1096 |
if not warnings: |
| 1097 |
return |
| 1098 |
|
| 1099 |
if self._warnings is None: |
| 1100 |
self._warnings = [] |
| 1101 |
|
| 1102 |
self._warnings.extend(warnings) |
| 1103 |
|
| 1104 |
def _extend_deprecations(self, deprecations: c.Iterable[_messages.DeprecationSummary]) -> None: |
| 1105 |
if not deprecations: |
| 1106 |
return |
| 1107 |
|
| 1108 |
if self._deprecations is None: |
| 1109 |
self._deprecations = [] |
| 1110 |
|
| 1111 |
self._deprecations.extend(deprecations) |
| 1112 |
|
| 1113 |
@classmethod |
| 1114 |
def convert_field(cls, resolved_field: ResolvedField, value: object) -> object: |
| 1115 |
if value is None: |
| 1116 |
return None if resolved_field.optional else resolved_field.field.default |
| 1117 |
|
| 1118 |
if resolved_field.type is _messages.ErrorSummary: |
| 1119 |
return value # RPFIX-5: VALIDATION: defer conversion to __post_init__ |
| 1120 |
|
| 1121 |
# RPFIX-5: VALIDATION: this doesn't handle special types like exception which require extra conversion |
| 1122 |
|
| 1123 |
if not resolved_field.metadata.conversion_func and isinstance(value, resolved_field.type): |
| 1124 |
return value |
| 1125 |
|
| 1126 |
# RPFIX-5: VALIDATION: this type checking doesn't validate types within containers (mapping, dict, etc.) |
| 1127 |
|
| 1128 |
help_text = f"Values for result key {resolved_field.result_key!r} must be of type {native_type_name(resolved_field.type)}." |
| 1129 |
|
| 1130 |
conversion_func = resolved_field.metadata.conversion_func or resolved_field.type |
| 1131 |
|
| 1132 |
try: |
| 1133 |
result = conversion_func(value) |
| 1134 |
except Exception: |
| 1135 |
result = resolved_field.field.default |
| 1136 |
display.warning( |
| 1137 |
f'Value for result key {resolved_field.result_key!r} of type {native_type_name(value)} was replaced with {result}.', |
| 1138 |
obj=value, |
| 1139 |
help_text=help_text, |
| 1140 |
) |
| 1141 |
else: |
| 1142 |
if not isinstance(value, resolved_field.type): |
| 1143 |
# RPFIX-5: UX: this will still give duplicate warnings -- probably just need to be explicit and have conversion funcs do warnings |
| 1144 |
display.warning( |
| 1145 |
msg=f'Value for result key {resolved_field.result_key!r} of type {native_type_name(value)} ' |
| 1146 |
f'was converted to {native_type_name(resolved_field.type)}.', |
| 1147 |
obj=value, |
| 1148 |
help_text=help_text, |
| 1149 |
) |
| 1150 |
|
| 1151 |
return result |
| 1152 |
|
| 1153 |
def __post_init__(self) -> None: |
| 1154 |
# Normalize the result `exception`, if any, to be a `CapturedErrorSummary` instance. |
| 1155 |
# If a new `CapturedErrorSummary` was created, the `error_type` will be `cls`. |
| 1156 |
# The `exception` key will be removed if falsey. |
| 1157 |
# A `CapturedErrorSummary` instance will be returned if `failed` is truthy. |
| 1158 |
if isinstance(self.exception, _captured.CapturedErrorSummary): |
| 1159 |
self.is_module = self.exception.is_module |
| 1160 |
elif isinstance(self.exception, _messages.ErrorSummary): |
| 1161 |
self.exception = _captured.CapturedErrorSummary( |
| 1162 |
event=self.exception.event, |
| 1163 |
error_context=self._captured_error_context, |
| 1164 |
error_message=self._captured_error_message, |
| 1165 |
is_module=self.is_module, |
| 1166 |
) |
| 1167 |
elif self.failed or self.exception: |
| 1168 |
# RPFIX-5: UX: warn/deprecate if exception is present without failed being True (and do what with failed?) |
| 1169 |
|
| 1170 |
# translate non-ErrorSummary errors |
| 1171 |
self.exception = _captured.CapturedErrorSummary( |
| 1172 |
event=_messages.Event( |
| 1173 |
msg=str(self.msg or 'Unknown error.'), |
| 1174 |
formatted_traceback=_normalize_traceback(self.exception), |
| 1175 |
), |
| 1176 |
error_context=self._captured_error_context, |
| 1177 |
error_message=self._captured_error_message, |
| 1178 |
is_module=self.is_module, |
| 1179 |
) |
| 1180 |
else: |
| 1181 |
self.exception = None |
| 1182 |
|
| 1183 |
@classmethod |
| 1184 |
def from_module_result_dict(cls, result: dict[str, object]) -> t.Self: |
| 1185 |
if (results := result.get('results', ...)) is not ... and (not isinstance(results, c.Sequence) or isinstance(results, str)): |
| 1186 |
# deprecated: description='deprecate the value of ansible_module_results' core_version='2.25' |
| 1187 |
# results = deprecate_value( |
| 1188 |
# value=results, |
| 1189 |
# msg="The 'ansible_module_results' result key is deprecated.", |
| 1190 |
# help_text="Use the 'results' result key instead.", |
| 1191 |
# version="2.29", |
| 1192 |
# ) |
| 1193 |
|
| 1194 |
result['ansible_module_results'] = results |
| 1195 |
|
| 1196 |
return cls._from_result_dict(result, source_is_module=True) |
| 1197 |
|
| 1198 |
@staticmethod |
| 1199 |
def create_from_module_exception(exception: BaseException, accept_result_contribution: bool = False) -> UnifiedTaskResult: |
| 1200 |
"""Return a failed task result dict from the given exception.""" |
| 1201 |
return UnifiedTaskResult._create_from_exception(exception, accept_result_contribution=accept_result_contribution, source_is_module=True) |
| 1202 |
|
| 1203 |
@staticmethod |
| 1204 |
def _create_from_exception(exception: BaseException, *, accept_result_contribution: bool = False, source_is_module: bool) -> UnifiedTaskResult: |
| 1205 |
"""Return a failed task result dict from the given exception.""" |
| 1206 |
event = _error_factory.ControllerEventFactory.from_exception(exception, _traceback.is_traceback_enabled(_traceback.TracebackEvent.ERROR)) |
| 1207 |
|
| 1208 |
omit_failed_key = False |
| 1209 |
omit_exception_key = False |
| 1210 |
utr = UnifiedTaskResult(is_module=source_is_module) |
| 1211 |
|
| 1212 |
if accept_result_contribution: |
| 1213 |
while exception: |
| 1214 |
if isinstance(exception, _error_utils.ContributesToTaskResult): |
| 1215 |
utr = exception.as_task_result(utr) |
| 1216 |
omit_failed_key = exception.omit_failed_key |
| 1217 |
omit_exception_key = exception.omit_exception_key |
| 1218 |
break |
| 1219 |
|
| 1220 |
exception = exception.__cause__ |
| 1221 |
|
| 1222 |
if omit_failed_key: |
| 1223 |
utr.failed = None |
| 1224 |
else: |
| 1225 |
utr.failed = True |
| 1226 |
|
| 1227 |
if omit_exception_key: |
| 1228 |
utr.exception = None |
| 1229 |
else: |
| 1230 |
utr.exception = _messages.ErrorSummary(event=event) |
| 1231 |
|
| 1232 |
if not utr.msg: |
| 1233 |
# if nothing contributed `msg`, generate one from the exception messages |
| 1234 |
utr.msg = _event_utils.format_event_brief_message(event) |
| 1235 |
|
| 1236 |
return utr |
| 1237 |
|
| 1238 |
def finalize_warnings(self, warning_ctx: _display_utils.DeferredWarningContext) -> None: |
| 1239 |
if warnings := warning_ctx.get_warnings(): |
| 1240 |
self._warnings = warnings |
| 1241 |
|
| 1242 |
if deprecation_warnings := warning_ctx.get_deprecation_warnings(): |
| 1243 |
self._deprecations = deprecation_warnings |
| 1244 |
|
| 1245 |
@property |
| 1246 |
def _captured_error_message(self) -> str: |
| 1247 |
return 'Module failed.' if self.is_module else 'Action failed.' |
| 1248 |
|
| 1249 |
@property |
| 1250 |
def _captured_error_context(self) -> str: |
| 1251 |
return 'target' if self.is_module else 'action' |
| 1252 |
|
| 1253 |
def set_fact(self, key: str, value: object) -> None: |
| 1254 |
if self.ansible_facts is None: |
| 1255 |
self.ansible_facts = {} |
| 1256 |
|
| 1257 |
self.ansible_facts[key] = value |
| 1258 |
|
| 1259 |
def remove_internal_keys(self): |
| 1260 |
# cleanse fact values that are allowed from actions but not modules |
| 1261 |
if self.ansible_facts: |
| 1262 |
for key in list(self.ansible_facts): |
| 1263 |
# RPFIX-5: IMPL: move this into the control plane and inject into the results as needed |
| 1264 |
if key.startswith('discovered_interpreter_') or key.startswith('ansible_discovered_interpreter_'): |
| 1265 |
self.ansible_facts.pop(key) |
| 1266 |
|
| 1267 |
@staticmethod |
| 1268 |
def create_from_action_exception(exception: BaseException, accept_result_contribution: bool = False) -> UnifiedTaskResult: |
| 1269 |
"""Return a failed task result dict from the given exception.""" |
| 1270 |
utr = UnifiedTaskResult._create_from_exception(exception, accept_result_contribution=accept_result_contribution, source_is_module=False) |
| 1271 |
|
| 1272 |
TaskContext.current()._record_result(utr) |
| 1273 |
|
| 1274 |
return utr |
| 1275 |
|
| 1276 |
@classmethod |
| 1277 |
@contextlib.contextmanager |
| 1278 |
def create_and_record(cls, result: dict[str, t.Any] | None = None) -> t.Generator[t.Self]: |
| 1279 |
utr = cls.from_action_result_dict(result or {}) |
| 1280 |
yield utr |
| 1281 |
TaskContext.current()._record_result(utr) |
| 1282 |
|
| 1283 |
def maybe_raise_on_result(self) -> None: |
| 1284 |
"""Raise an exception if the result indicated failure.""" |
| 1285 |
if self.exception and self.failed: # even though error detail was normalized, only raise it if the result indicated failure |
| 1286 |
raise _captured.AnsibleResultCapturedError(self.exception.event, self) |
| 1287 |
|
| 1288 |
def set_skipped(self, reason: str | None = None, include_skipped_reason: bool = False) -> None: |
| 1289 |
self.changed = False |
| 1290 |
self.skipped = True |
| 1291 |
|
| 1292 |
if reason: |
| 1293 |
self.skip_reason = reason |
| 1294 |
|
| 1295 |
if include_skipped_reason: |
| 1296 |
self.skipped_reason = deprecate_value( |
| 1297 |
value=reason, |
| 1298 |
msg="The 'skipped_reason' value is deprecated.", |
| 1299 |
help_text="Use 'skip_reason' instead.", |
| 1300 |
version="2.24", |
| 1301 |
) |
| 1302 |
|
| 1303 |
@classmethod |
| 1304 |
def record_conditional_false(cls, conditional_expression: object) -> t.Self: |
| 1305 |
with cls.create_and_record() as utr: |
| 1306 |
utr.set_skipped('Conditional result was False') |
| 1307 |
utr.false_condition = conditional_expression |
| 1308 |
|
| 1309 |
return utr |
| 1310 |
|
| 1311 |
def set_break_when_result(self, value: bool | AnsibleError) -> None: |
| 1312 |
task_ctx = TaskContext.current() |
| 1313 |
|
| 1314 |
result: bool | str |
| 1315 |
|
| 1316 |
if isinstance(value, bool): |
| 1317 |
result = value |
| 1318 |
break_when = value |
| 1319 |
else: |
| 1320 |
result = str(value) |
| 1321 |
|
| 1322 |
try: |
| 1323 |
# The original error's obj should contain the failed expression, which should be origin tagged. |
| 1324 |
# This error is intended to provide additional context (the message) for the original error. |
| 1325 |
# By repeating the original error's obj here, the error display will group the two errors together. |
| 1326 |
raise AnsibleError("A 'break_when' expression failed.", obj=value.obj) from value |
| 1327 |
except Exception as ex: |
| 1328 |
wrapped_ex = ex |
| 1329 |
|
| 1330 |
break_when = True |
| 1331 |
|
| 1332 |
if self.exception: |
| 1333 |
self.break_when_suppressed_exception = self.exception |
| 1334 |
|
| 1335 |
self.failed = True |
| 1336 |
self.exception = _messages.ErrorSummary( |
| 1337 |
# pylint: disable=used-before-assignment |
| 1338 |
event=_error_factory.ControllerEventFactory.from_exception(wrapped_ex, _traceback.is_traceback_enabled(_traceback.TracebackEvent.ERROR)), |
| 1339 |
) |
| 1340 |
|
| 1341 |
if break_when: |
| 1342 |
task_ctx._break_when_triggered = True |
| 1343 |
task_ctx._has_loop_exited = True |
| 1344 |
|
| 1345 |
self.break_when_result = result |
| 1346 |
|
| 1347 |
def set_changed_when_result(self, value: bool | AnsibleError) -> None: |
| 1348 |
result: bool | str |
| 1349 |
|
| 1350 |
if isinstance(value, bool): |
| 1351 |
result = value |
| 1352 |
|
| 1353 |
self.changed = value |
| 1354 |
else: |
| 1355 |
if self.exception: |
| 1356 |
self.changed_when_suppressed_exception = self.exception |
| 1357 |
|
| 1358 |
result = str(value) |
| 1359 |
|
| 1360 |
try: |
| 1361 |
# The original error's obj should contain the failed expression, which should be origin tagged. |
| 1362 |
# This error is intended to provide additional context (the message) for the original error. |
| 1363 |
# By repeating the original error's obj here, the error display will group the two errors together. |
| 1364 |
raise AnsibleError("A 'changed_when' expression failed.", obj=value.obj) from value |
| 1365 |
except Exception as ex: |
| 1366 |
wrapped_ex = ex |
| 1367 |
|
| 1368 |
self.failed = True |
| 1369 |
self.exception = _messages.ErrorSummary( |
| 1370 |
# pylint: disable=used-before-assignment |
| 1371 |
event=_error_factory.ControllerEventFactory.from_exception(wrapped_ex, _traceback.is_traceback_enabled(_traceback.TracebackEvent.ERROR)), |
| 1372 |
) |
| 1373 |
|
| 1374 |
self.changed_when_result = result |
| 1375 |
|
| 1376 |
def set_failed_when_result(self, value: bool | AnsibleError) -> None: |
| 1377 |
# RPFIX-5: DOC: document exception suppression logic in changelog et al |
| 1378 |
# The use of any failed_when expression will suppress the existing value of `exception` and store it in `failed_when_suppressed_exception`, |
| 1379 |
# regardless if the expression result is True, False, or an exception. For True and exception, the `exception` value in the task result becomes |
| 1380 |
# one generated (or caused) by failed_when. |
| 1381 |
|
| 1382 |
if self.exception: |
| 1383 |
self.failed_when_suppressed_exception = self.exception |
| 1384 |
self.exception = None |
| 1385 |
|
| 1386 |
result: bool | str |
| 1387 |
|
| 1388 |
if isinstance(value, bool): |
| 1389 |
result = value |
| 1390 |
|
| 1391 |
self.failed = value |
| 1392 |
|
| 1393 |
if value: |
| 1394 |
event = _messages.Event( |
| 1395 |
msg="A 'failed_when' expression evaluated to 'True'.", |
| 1396 |
# RPFIX-5: UX: We should be able to show more useful information here than just a static message, |
| 1397 |
# including any shadowed msg we may have had and the (origin-tagged) failed_when expression itself. |
| 1398 |
# chain=None if self.msg is None else _messages.EventChain( |
| 1399 |
# msg_reason='DO THINGS HERE', |
| 1400 |
# traceback_reason='DO THINGS HERE', |
| 1401 |
# event=_messages.Event( |
| 1402 |
# msg=str(self.msg), |
| 1403 |
# help_text="This was the original 'msg' before 'failed_when' was evaluated.", |
| 1404 |
# ), |
| 1405 |
# ), |
| 1406 |
) |
| 1407 |
|
| 1408 |
self.exception = _messages.ErrorSummary( |
| 1409 |
event=event, |
| 1410 |
) |
| 1411 |
else: |
| 1412 |
result = str(value) |
| 1413 |
|
| 1414 |
try: |
| 1415 |
# The original error's obj should contain the failed expression, which should be origin tagged. |
| 1416 |
# This error is intended to provide additional context (the message) for the original error. |
| 1417 |
# By repeating the original error's obj here, the error display will group the two errors together. |
| 1418 |
raise AnsibleError("A 'failed_when' expression failed.", obj=value.obj) from value |
| 1419 |
except Exception as ex: |
| 1420 |
wrapped_ex = ex |
| 1421 |
|
| 1422 |
self.failed = True |
| 1423 |
self.exception = _messages.ErrorSummary( |
| 1424 |
# pylint: disable=used-before-assignment |
| 1425 |
event=_error_factory.ControllerEventFactory.from_exception(wrapped_ex, _traceback.is_traceback_enabled(_traceback.TracebackEvent.ERROR)), |
| 1426 |
) |
| 1427 |
|
| 1428 |
self.failed_when_result = result |
| 1429 |
|
| 1430 |
|
| 1431 |
def _normalize_traceback(value: object | None) -> str | None: |
| 1432 |
"""Normalize the provided traceback value, returning None if it is falsey.""" |
| 1433 |
if not value: |
| 1434 |
return None |
| 1435 |
|
| 1436 |
value = str(value).rstrip() |
| 1437 |
|
| 1438 |
if not value: |
| 1439 |
return None |
| 1440 |
|
| 1441 |
return value + '\n' |
| 1442 |
|
| 1443 |
|
| 1444 |
@t.final |
| 1445 |
@dataclasses.dataclass(frozen=True, kw_only=True, slots=True) |
| 1446 |
class WireTaskResult: |
| 1447 |
host_name: str |
| 1448 |
task_uuid: str |
| 1449 |
task_fields: c.Mapping[str, object] |
| 1450 |
utr: UnifiedTaskResult |
| 1451 |
|
| 1452 |
@classmethod |
| 1453 |
def create(cls, host: Host, task: Task, utr: UnifiedTaskResult) -> t.Self: |
| 1454 |
return cls( |
| 1455 |
host_name=host.name, |
| 1456 |
task_uuid=task._uuid, |
| 1457 |
utr=utr, |
| 1458 |
task_fields=task.dump_attrs(), |
| 1459 |
) |
| 1460 |
|
| 1461 |
|
| 1462 |
@t.final |
| 1463 |
@dataclasses.dataclass(frozen=True, kw_only=True, slots=True) |
| 1464 |
class HostTaskResult: |
| 1465 |
host: Host |
| 1466 |
task: Task |
| 1467 |
utr: UnifiedTaskResult |