| 1 |
# (c) 2012-2014, Michael DeHaan <[email protected]> |
| 2 |
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 3 |
|
| 4 |
from __future__ import annotations |
| 5 |
|
| 6 |
import collections.abc as _c |
| 7 |
import enum |
| 8 |
import types |
| 9 |
import typing as t |
| 10 |
|
| 11 |
from json import JSONDecodeError |
| 12 |
|
| 13 |
from ansible.module_utils.common.text.converters import to_text |
| 14 |
from ..module_utils.datatag import native_type_name |
| 15 |
from ansible._internal._datatag import _tags |
| 16 |
from .._internal._errors import _error_utils |
| 17 |
from ansible.module_utils._internal import _text_utils |
| 18 |
|
| 19 |
if t.TYPE_CHECKING: |
| 20 |
from ansible.plugins import loader as _t_loader |
| 21 |
from .._internal import _task as _t_task |
| 22 |
|
| 23 |
|
| 24 |
class ExitCode(enum.IntEnum): |
| 25 |
SUCCESS = 0 # used by TQM, must be bit-flag safe |
| 26 |
GENERIC_ERROR = 1 # used by TQM, must be bit-flag safe |
| 27 |
HOST_FAILED = 2 # TQM-sourced, must be bit-flag safe |
| 28 |
HOST_UNREACHABLE = 4 # TQM-sourced, must be bit-flag safe |
| 29 |
PARSER_ERROR = 4 # FIXME: CLI-sourced, conflicts with HOST_UNREACHABLE |
| 30 |
INVALID_CLI_OPTION = 5 |
| 31 |
UNICODE_ERROR = 6 # obsolete, no longer used |
| 32 |
KEYBOARD_INTERRUPT = 99 |
| 33 |
UNKNOWN_ERROR = 250 |
| 34 |
|
| 35 |
|
| 36 |
class AnsibleError(Exception): |
| 37 |
""" |
| 38 |
This is the base class for all errors raised from Ansible code, |
| 39 |
and can be instantiated with two optional parameters beyond the |
| 40 |
error message to control whether detailed information is displayed |
| 41 |
when the error occurred while parsing a data file of some kind. |
| 42 |
|
| 43 |
Usage: |
| 44 |
|
| 45 |
raise AnsibleError('some message here', obj=obj) |
| 46 |
|
| 47 |
Where "obj" may be tagged with Origin to provide context for error messages. |
| 48 |
""" |
| 49 |
|
| 50 |
_exit_code = ExitCode.GENERIC_ERROR |
| 51 |
_default_message = '' |
| 52 |
_default_help_text: str | None = None |
| 53 |
_include_cause_message = True |
| 54 |
""" |
| 55 |
When `True`, the exception message will be augmented with cause message(s). |
| 56 |
Subclasses doing complex error analysis can disable this to take responsibility for reporting cause messages as needed. |
| 57 |
""" |
| 58 |
|
| 59 |
def __init__( |
| 60 |
self, |
| 61 |
message: str = "", |
| 62 |
obj: t.Any = None, |
| 63 |
show_content: bool = True, |
| 64 |
suppress_extended_error: bool | types.EllipsisType = ..., |
| 65 |
orig_exc: BaseException | None = None, |
| 66 |
help_text: str | None = None, |
| 67 |
) -> None: |
| 68 |
# DTFIX-FUTURE: these fallback cases mask incorrect use of AnsibleError.message, what should we do? |
| 69 |
if message is None: |
| 70 |
message = '' |
| 71 |
elif not isinstance(message, str): |
| 72 |
message = str(message) |
| 73 |
|
| 74 |
if self._default_message and message: |
| 75 |
message = _text_utils.concat_message(self._default_message, message) |
| 76 |
elif self._default_message: |
| 77 |
message = self._default_message |
| 78 |
elif not message: |
| 79 |
message = f'Unexpected {type(self).__name__} error.' |
| 80 |
|
| 81 |
super().__init__(message) |
| 82 |
|
| 83 |
self._show_content = show_content |
| 84 |
self._message = message |
| 85 |
self._help_text_value = help_text or self._default_help_text |
| 86 |
self.obj = obj |
| 87 |
|
| 88 |
# deprecated: description='deprecate support for orig_exc, callers should use `raise ... from` only' core_version='2.23' |
| 89 |
# deprecated: description='remove support for orig_exc' core_version='2.27' |
| 90 |
self.orig_exc = orig_exc |
| 91 |
|
| 92 |
if suppress_extended_error is not ...: |
| 93 |
from ..utils.display import Display |
| 94 |
|
| 95 |
if suppress_extended_error: |
| 96 |
self._show_content = False |
| 97 |
|
| 98 |
Display().deprecated( |
| 99 |
msg=f"The `suppress_extended_error` argument to `{type(self).__name__}` is deprecated.", |
| 100 |
version="2.23", |
| 101 |
help_text="Use `show_content=False` instead.", |
| 102 |
) |
| 103 |
|
| 104 |
@property |
| 105 |
def _original_message(self) -> str: |
| 106 |
return self._message |
| 107 |
|
| 108 |
@property |
| 109 |
def message(self) -> str: |
| 110 |
""" |
| 111 |
Return the original message with cause message(s) appended. |
| 112 |
The cause will not be followed on any `AnsibleError` with `_include_cause_message=False`. |
| 113 |
""" |
| 114 |
return _error_utils.format_exception_message(self) |
| 115 |
|
| 116 |
@message.setter |
| 117 |
def message(self, val) -> None: |
| 118 |
self._message = val |
| 119 |
|
| 120 |
@property |
| 121 |
def _formatted_source_context(self) -> str | None: |
| 122 |
with _error_utils.RedactAnnotatedSourceContext.when(not self._show_content): |
| 123 |
if source_context := _error_utils.SourceContext.from_value(self.obj): |
| 124 |
return str(source_context) |
| 125 |
|
| 126 |
return None |
| 127 |
|
| 128 |
@property |
| 129 |
def _help_text(self) -> str | None: |
| 130 |
return self._help_text_value |
| 131 |
|
| 132 |
@_help_text.setter |
| 133 |
def _help_text(self, value: str | None) -> None: |
| 134 |
self._help_text_value = value |
| 135 |
|
| 136 |
def __str__(self) -> str: |
| 137 |
return self.message |
| 138 |
|
| 139 |
def __getstate__(self) -> dict[str, t.Any]: |
| 140 |
"""Augment object.__getstate__ to preserve additional values not represented in BaseException.__dict__.""" |
| 141 |
state = t.cast(dict[str, t.Any], super().__getstate__()) |
| 142 |
state.update( |
| 143 |
args=self.args, |
| 144 |
__cause__=self.__cause__, |
| 145 |
__context__=self.__context__, |
| 146 |
__suppress_context__=self.__suppress_context__, |
| 147 |
) |
| 148 |
|
| 149 |
return state |
| 150 |
|
| 151 |
def __reduce__(self) -> tuple[t.Callable, tuple[type], dict[str, t.Any]]: |
| 152 |
""" |
| 153 |
Enable copy/pickle of AnsibleError derived types by correcting for BaseException's ancient C __reduce__ impl that: |
| 154 |
|
| 155 |
* requires use of a type constructor with positional args |
| 156 |
* assumes positional args are passed through from the derived type __init__ to BaseException.__init__ unmodified |
| 157 |
* does not propagate args/__cause__/__context__/__suppress_context__ |
| 158 |
|
| 159 |
NOTE: This does not preserve the dunder attributes on non-AnsibleError derived cause/context exceptions. |
| 160 |
As a result, copy/pickle will discard chained exceptions after the first non-AnsibleError cause/context. |
| 161 |
""" |
| 162 |
return type(self).__new__, (type(self),), self.__getstate__() |
| 163 |
|
| 164 |
|
| 165 |
class AnsibleUndefinedConfigEntry(AnsibleError): |
| 166 |
"""The requested config entry is not defined.""" |
| 167 |
|
| 168 |
|
| 169 |
class AnsibleTaskError(AnsibleError): |
| 170 |
"""Task execution failed; provides contextual information about the task.""" |
| 171 |
|
| 172 |
_default_message = 'Task failed.' |
| 173 |
|
| 174 |
|
| 175 |
class AnsiblePromptInterrupt(AnsibleError): |
| 176 |
"""User interrupt.""" |
| 177 |
|
| 178 |
|
| 179 |
class AnsiblePromptNoninteractive(AnsibleError): |
| 180 |
"""Unable to get user input.""" |
| 181 |
|
| 182 |
|
| 183 |
class AnsibleAssertionError(AnsibleError, AssertionError): |
| 184 |
"""Invalid assertion.""" |
| 185 |
|
| 186 |
|
| 187 |
class AnsibleOptionsError(AnsibleError): |
| 188 |
"""Invalid options were passed.""" |
| 189 |
|
| 190 |
# FIXME: This exception is used for many non-CLI related errors. |
| 191 |
# The few cases which are CLI related should really be handled by argparse instead, at which point the exit code here can be removed. |
| 192 |
_exit_code = ExitCode.INVALID_CLI_OPTION |
| 193 |
|
| 194 |
|
| 195 |
class AnsibleRequiredOptionError(AnsibleOptionsError): |
| 196 |
"""Bad or incomplete options passed.""" |
| 197 |
|
| 198 |
|
| 199 |
class AnsibleParserError(AnsibleError): |
| 200 |
"""A playbook or data file could not be parsed.""" |
| 201 |
|
| 202 |
_exit_code = ExitCode.PARSER_ERROR |
| 203 |
|
| 204 |
|
| 205 |
class AnsibleFieldAttributeError(AnsibleParserError): |
| 206 |
"""Errors caused during field attribute processing.""" |
| 207 |
|
| 208 |
|
| 209 |
class AnsibleJSONParserError(AnsibleParserError): |
| 210 |
"""JSON-specific parsing failure wrapping an exception raised by the JSON parser.""" |
| 211 |
|
| 212 |
_default_message = 'JSON parsing failed.' |
| 213 |
_include_cause_message = False # hide the underlying cause message, it's included by `handle_exception` as needed |
| 214 |
|
| 215 |
@classmethod |
| 216 |
def handle_exception(cls, exception: Exception, origin: _tags.Origin) -> t.NoReturn: |
| 217 |
if isinstance(exception, JSONDecodeError): |
| 218 |
origin = origin.replace(line_num=exception.lineno, col_num=exception.colno) |
| 219 |
|
| 220 |
message = str(exception) |
| 221 |
|
| 222 |
error = cls(message, obj=origin) |
| 223 |
|
| 224 |
raise error from exception |
| 225 |
|
| 226 |
|
| 227 |
class AnsibleInternalError(AnsibleError): |
| 228 |
"""Internal safeguards tripped, something happened in the code that should never happen.""" |
| 229 |
|
| 230 |
|
| 231 |
class AnsibleRuntimeError(AnsibleError): |
| 232 |
"""Ansible had a problem while running a playbook.""" |
| 233 |
|
| 234 |
|
| 235 |
class AnsibleModuleError(AnsibleRuntimeError): |
| 236 |
"""A module failed somehow.""" |
| 237 |
|
| 238 |
|
| 239 |
class AnsibleConnectionFailure(AnsibleRuntimeError, _error_utils.ContributesToTaskResult): |
| 240 |
""" |
| 241 |
The transport / connection_plugin had a fatal error. |
| 242 |
|
| 243 |
This exception provides a result dictionary via the ContributesToTaskResult mixin. |
| 244 |
""" |
| 245 |
|
| 246 |
def as_task_result(self, utr: _t_task.UnifiedTaskResult) -> _t_task.UnifiedTaskResult: |
| 247 |
utr.unreachable = True |
| 248 |
|
| 249 |
return utr |
| 250 |
|
| 251 |
@property |
| 252 |
def omit_failed_key(self) -> bool: |
| 253 |
return True |
| 254 |
|
| 255 |
|
| 256 |
class AnsibleAuthenticationFailure(AnsibleConnectionFailure): |
| 257 |
"""Invalid username/password/key.""" |
| 258 |
|
| 259 |
_default_message = "Failed to authenticate." |
| 260 |
|
| 261 |
|
| 262 |
class AnsibleCallbackError(AnsibleRuntimeError): |
| 263 |
"""A callback failure.""" |
| 264 |
|
| 265 |
|
| 266 |
class AnsibleTemplateError(AnsibleRuntimeError): |
| 267 |
"""A template related error.""" |
| 268 |
|
| 269 |
|
| 270 |
class TemplateTrustCheckFailedError(AnsibleTemplateError): |
| 271 |
"""Raised when processing was requested on an untrusted template or expression.""" |
| 272 |
|
| 273 |
_default_message = 'Encountered untrusted template or expression.' |
| 274 |
_default_help_text = ('Templates and expressions must be defined by trusted sources such as playbooks or roles, ' |
| 275 |
'not untrusted sources such as module results.') |
| 276 |
|
| 277 |
|
| 278 |
class AnsibleTemplateTransformLimitError(AnsibleTemplateError): |
| 279 |
"""The internal template transform limit was exceeded.""" |
| 280 |
|
| 281 |
_default_message = "Template transform limit exceeded." |
| 282 |
|
| 283 |
|
| 284 |
class AnsibleTemplateSyntaxError(AnsibleTemplateError): |
| 285 |
"""A syntax error was encountered while parsing a Jinja template or expression.""" |
| 286 |
|
| 287 |
|
| 288 |
class AnsibleBrokenConditionalError(AnsibleTemplateError): |
| 289 |
"""A broken conditional with non-boolean result was used.""" |
| 290 |
|
| 291 |
_default_help_text = 'Broken conditionals can be temporarily allowed with the `ALLOW_BROKEN_CONDITIONALS` configuration option.' |
| 292 |
|
| 293 |
|
| 294 |
class AnsibleUndefinedVariable(AnsibleTemplateError): |
| 295 |
"""An undefined variable was encountered while processing a template or expression.""" |
| 296 |
|
| 297 |
|
| 298 |
class AnsibleValueOmittedError(AnsibleTemplateError): |
| 299 |
""" |
| 300 |
Raised when the result of a template operation was the Omit singleton. This exception purposely does |
| 301 |
not derive from AnsibleError to avoid elision of the traceback, since uncaught errors of this type always |
| 302 |
indicate a bug. |
| 303 |
""" |
| 304 |
|
| 305 |
_default_message = "A template was resolved to an Omit scalar." |
| 306 |
_default_help_text = "Callers must be prepared to handle this value. This is most likely a bug in the code requesting templating." |
| 307 |
|
| 308 |
|
| 309 |
class AnsibleTemplatePluginError(AnsibleTemplateError): |
| 310 |
"""An error sourced by a template plugin (lookup/filter/test).""" |
| 311 |
|
| 312 |
|
| 313 |
# deprecated: description='add deprecation warnings for these aliases' core_version='2.23' |
| 314 |
AnsibleFilterError = AnsibleTemplatePluginError |
| 315 |
AnsibleLookupError = AnsibleTemplatePluginError |
| 316 |
|
| 317 |
|
| 318 |
class AnsibleFileNotFound(AnsibleRuntimeError): |
| 319 |
"""A file missing failure.""" |
| 320 |
|
| 321 |
_default_help_text = "If you are using a module and expect the file to exist on the remote, see the remote_src option." |
| 322 |
|
| 323 |
def __init__(self, message="", obj=None, show_content=True, suppress_extended_error=..., orig_exc=None, paths=None, file_name=None): |
| 324 |
|
| 325 |
self.file_name = file_name |
| 326 |
self.paths = paths |
| 327 |
|
| 328 |
if message: |
| 329 |
message += " " |
| 330 |
|
| 331 |
if self.file_name: |
| 332 |
message += "Could not find or access '%s'" % to_text(self.file_name) |
| 333 |
else: |
| 334 |
message += "Could not find file" |
| 335 |
|
| 336 |
if self.paths and isinstance(self.paths, _c.Sequence): |
| 337 |
searched = to_text('\n\t'.join(self.paths)) |
| 338 |
if message: |
| 339 |
message += "\n" |
| 340 |
message += "Searched in:\n\t%s" % searched |
| 341 |
|
| 342 |
message += " on the Ansible Controller." |
| 343 |
|
| 344 |
super(AnsibleFileNotFound, self).__init__(message=message, obj=obj, show_content=show_content, |
| 345 |
suppress_extended_error=suppress_extended_error, orig_exc=orig_exc) |
| 346 |
|
| 347 |
|
| 348 |
class AnsibleAction(AnsibleRuntimeError, _error_utils.ContributesToTaskResult): |
| 349 |
"""Base Exception for Action plugin flow control.""" |
| 350 |
|
| 351 |
def __init__(self, message="", obj=None, show_content=True, suppress_extended_error=..., orig_exc=None, result=None): |
| 352 |
super().__init__(message=message, obj=obj, show_content=show_content, suppress_extended_error=suppress_extended_error, orig_exc=orig_exc) |
| 353 |
|
| 354 |
self._result = result or {} |
| 355 |
|
| 356 |
def as_task_result(self, utr: _t_task.UnifiedTaskResult) -> _t_task.UnifiedTaskResult: |
| 357 |
utr.result_data.update(self._result) |
| 358 |
|
| 359 |
return utr |
| 360 |
|
| 361 |
@property |
| 362 |
def result(self) -> dict[str, object]: |
| 363 |
"""Backward compatibility property returning a mutable dictionary.""" |
| 364 |
return self._result |
| 365 |
|
| 366 |
|
| 367 |
class AnsibleActionSkip(AnsibleAction): # deprecated: description='remove class AnsibleActionSkip', core_version='2.25' |
| 368 |
""" |
| 369 |
An action runtime skip. |
| 370 |
|
| 371 |
This exception provides a result dictionary via the ContributesToTaskResult mixin. |
| 372 |
|
| 373 |
DEPRECATED for removal in 2.25 |
| 374 |
""" |
| 375 |
|
| 376 |
def as_task_result(self, utr: _t_task.UnifiedTaskResult) -> _t_task.UnifiedTaskResult: |
| 377 |
utr = super().as_task_result(utr) |
| 378 |
utr.skipped = True |
| 379 |
utr.msg = self.message |
| 380 |
|
| 381 |
return utr |
| 382 |
|
| 383 |
@property |
| 384 |
def omit_failed_key(self) -> bool: |
| 385 |
return True |
| 386 |
|
| 387 |
@property |
| 388 |
def omit_exception_key(self) -> bool: |
| 389 |
return True |
| 390 |
|
| 391 |
|
| 392 |
class AnsibleActionNoCheckMode(AnsibleAction): |
| 393 |
""" |
| 394 |
An action runtime indication of lack of check_mode support. |
| 395 |
|
| 396 |
This exception provides a result dictionary via the ContributesToTaskResult mixin. |
| 397 |
|
| 398 |
Replacement for AnsibleActionSkip that does not return skipped=True. |
| 399 |
Available for use in ansible-core 2.23+. |
| 400 |
""" |
| 401 |
|
| 402 |
def as_task_result(self, utr: _t_task.UnifiedTaskResult) -> _t_task.UnifiedTaskResult: |
| 403 |
utr = super().as_task_result(utr) |
| 404 |
utr.changed = False |
| 405 |
utr.msg = self.message |
| 406 |
|
| 407 |
return utr |
| 408 |
|
| 409 |
@property |
| 410 |
def omit_failed_key(self) -> bool: |
| 411 |
return True |
| 412 |
|
| 413 |
@property |
| 414 |
def omit_exception_key(self) -> bool: |
| 415 |
return True |
| 416 |
|
| 417 |
|
| 418 |
class AnsibleActionFail(AnsibleAction): |
| 419 |
""" |
| 420 |
An action runtime failure. |
| 421 |
|
| 422 |
This exception provides a result dictionary via the ContributesToTaskResult mixin. |
| 423 |
""" |
| 424 |
|
| 425 |
def as_task_result(self, utr: _t_task.UnifiedTaskResult) -> _t_task.UnifiedTaskResult: |
| 426 |
utr = super().as_task_result(utr) |
| 427 |
utr.failed = True |
| 428 |
utr.msg = self.message |
| 429 |
|
| 430 |
return utr |
| 431 |
|
| 432 |
|
| 433 |
class _ActionDone(AnsibleAction): |
| 434 |
""" |
| 435 |
Imports as `_AnsibleActionDone` are deprecated. An action runtime early exit. |
| 436 |
|
| 437 |
This exception provides a result dictionary via the ContributesToTaskResult mixin. |
| 438 |
""" |
| 439 |
|
| 440 |
@property |
| 441 |
def omit_failed_key(self) -> bool: |
| 442 |
return not self._result.get('failed') |
| 443 |
|
| 444 |
@property |
| 445 |
def omit_exception_key(self) -> bool: |
| 446 |
return not self._result.get('failed') |
| 447 |
|
| 448 |
|
| 449 |
class AnsiblePluginError(AnsibleError): |
| 450 |
"""Base class for Ansible plugin-related errors that do not need AnsibleError contextual data.""" |
| 451 |
|
| 452 |
def __init__(self, message: str | None = None, plugin_load_context: _t_loader.PluginLoadContext | None = None, help_text: str | None = None) -> None: |
| 453 |
super(AnsiblePluginError, self).__init__(message, help_text=help_text) |
| 454 |
|
| 455 |
self.plugin_load_context = plugin_load_context |
| 456 |
|
| 457 |
|
| 458 |
class AnsiblePluginRemovedError(AnsiblePluginError): |
| 459 |
"""A requested plugin has been removed.""" |
| 460 |
|
| 461 |
|
| 462 |
class AnsiblePluginCircularRedirect(AnsiblePluginError): |
| 463 |
"""A cycle was detected in plugin redirection.""" |
| 464 |
|
| 465 |
|
| 466 |
class AnsibleCollectionUnsupportedVersionError(AnsiblePluginError): |
| 467 |
"""A collection is not supported by this version of Ansible.""" |
| 468 |
|
| 469 |
|
| 470 |
class AnsibleTypeError(AnsibleRuntimeError, TypeError): |
| 471 |
"""Ansible-augmented TypeError subclass.""" |
| 472 |
|
| 473 |
|
| 474 |
class AnsiblePluginNotFound(AnsiblePluginError): |
| 475 |
"""Indicates we did not find an Ansible plugin.""" |
| 476 |
|
| 477 |
|
| 478 |
class AnsibleConditionalError(AnsibleRuntimeError): |
| 479 |
"""Errors related to failed conditional expression evaluation.""" |
| 480 |
|
| 481 |
|
| 482 |
class AnsibleVariableTypeError(AnsibleRuntimeError): |
| 483 |
"""An error due to attempted storage of an unsupported variable type.""" |
| 484 |
|
| 485 |
@classmethod |
| 486 |
def from_value(cls, *, obj: t.Any) -> t.Self: |
| 487 |
# avoid an incorrect error message when `obj` is a type |
| 488 |
type_name = type(obj).__name__ if isinstance(obj, type) else native_type_name(obj) |
| 489 |
|
| 490 |
return cls(message=f'Type {type_name!r} is unsupported for variable storage.', obj=obj) |
| 491 |
|
| 492 |
|
| 493 |
def __getattr__(name: str) -> t.Any: |
| 494 |
"""Inject import-time deprecation warnings.""" |
| 495 |
from ..utils.display import Display |
| 496 |
|
| 497 |
match name: |
| 498 |
case 'AnsibleFilterTypeError': |
| 499 |
Display().deprecated( |
| 500 |
msg=f"Importing {name!r} is deprecated.", |
| 501 |
help_text=f"Import {AnsibleTypeError.__name__!r} instead.", |
| 502 |
version="2.23", |
| 503 |
) |
| 504 |
|
| 505 |
return AnsibleTypeError |
| 506 |
|
| 507 |
case '_AnsibleActionDone': |
| 508 |
Display().deprecated( |
| 509 |
msg=f"Importing {name!r} is deprecated.", |
| 510 |
help_text="Return directly from action plugins instead.", |
| 511 |
version="2.23", |
| 512 |
) |
| 513 |
|
| 514 |
return _ActionDone |
| 515 |
|
| 516 |
raise AttributeError(f'module {__name__!r} has no attribute {name!r}') |