0
# Error Handling and Exceptions
1
2
Ansible Core provides a comprehensive exception hierarchy that enables precise error handling and debugging throughout the automation process. All exceptions derive from `AnsibleError` and provide contextual information including source location, help text, and structured error reporting.
3
4
## Capabilities
5
6
### Base Exception System
7
8
The foundation exception class providing error message formatting, source context, and extensible error reporting for all Ansible operations.
9
10
```python { .api }
11
class AnsibleError(Exception):
12
"""
13
Base class for all errors raised from Ansible code.
14
15
Parameters:
16
- message: Error message string
17
- obj: Object that caused the error (for context)
18
- show_content: Whether to show source content in error
19
- help_text: Additional help information
20
21
Attributes:
22
- message: Formatted error message with cause information
23
- _original_message: Original error message without cause
24
- _help_text: Help text for resolving the error
25
"""
26
27
def __init__(self, message="", obj=None, show_content=True, help_text=None):
28
"""Initialize base Ansible error"""
29
30
class ExitCode(enum.IntEnum):
31
"""
32
Exit codes for Ansible CLI commands.
33
"""
34
SUCCESS = 0
35
GENERIC_ERROR = 1
36
HOST_FAILED = 2
37
HOST_UNREACHABLE = 4
38
PARSER_ERROR = 4
39
INVALID_CLI_OPTION = 5
40
KEYBOARD_INTERRUPT = 99
41
UNKNOWN_ERROR = 250
42
```
43
44
### Configuration Errors
45
46
Errors related to Ansible configuration including missing required options, invalid configuration values, and undefined configuration entries.
47
48
```python { .api }
49
class AnsibleOptionsError(AnsibleError):
50
"""
51
Invalid options were passed.
52
53
Used for CLI argument validation and configuration errors.
54
"""
55
56
class AnsibleRequiredOptionError(AnsibleOptionsError):
57
"""
58
Bad or incomplete options passed.
59
60
Raised when required CLI options or configuration values are missing.
61
"""
62
63
class AnsibleUndefinedConfigEntry(AnsibleError):
64
"""
65
The requested config entry is not defined.
66
67
Raised when attempting to access non-existent configuration keys.
68
"""
69
```
70
71
### Parser Errors
72
73
Errors encountered during YAML, JSON, and playbook parsing including syntax errors, field validation failures, and data structure problems.
74
75
```python { .api }
76
class AnsibleParserError(AnsibleError):
77
"""
78
A playbook or data file could not be parsed.
79
80
Raised for YAML syntax errors, invalid field values, and structural problems.
81
"""
82
83
class AnsibleFieldAttributeError(AnsibleParserError):
84
"""
85
Errors caused during field attribute processing.
86
87
Raised when task or play fields contain invalid values or structures.
88
"""
89
90
class AnsibleJSONParserError(AnsibleParserError):
91
"""
92
JSON-specific parsing failure wrapping an exception raised by the JSON parser.
93
94
Provides enhanced error reporting for JSON parsing issues.
95
"""
96
97
@classmethod
98
def handle_exception(cls, exception, origin):
99
"""
100
Convert JSON parsing exceptions to Ansible errors.
101
102
Parameters:
103
- exception: Original JSON parsing exception
104
- origin: Source location information
105
106
Raises:
107
AnsibleJSONParserError: Wrapped exception with context
108
"""
109
```
110
111
### Runtime Execution Errors
112
113
Errors that occur during playbook and task execution including module failures, connection issues, and general runtime problems.
114
115
```python { .api }
116
class AnsibleRuntimeError(AnsibleError):
117
"""
118
Ansible had a problem while running a playbook.
119
120
Base class for all runtime execution errors.
121
"""
122
123
class AnsibleModuleError(AnsibleRuntimeError):
124
"""
125
A module failed somehow.
126
127
Raised when modules return failure states or encounter execution errors.
128
"""
129
130
class AnsibleTaskError(AnsibleError):
131
"""
132
Task execution failed; provides contextual information about the task.
133
134
Enhanced error reporting for task-level failures with task context.
135
"""
136
137
class AnsibleInternalError(AnsibleError):
138
"""
139
Internal safeguards tripped, something happened in the code that should never happen.
140
141
Used for defensive programming and internal consistency checks.
142
"""
143
```
144
145
### Connection and Authentication Errors
146
147
Errors related to connecting to managed hosts including network failures, authentication problems, and transport issues.
148
149
```python { .api }
150
class AnsibleConnectionFailure(AnsibleRuntimeError):
151
"""
152
The transport / connection_plugin had a fatal error.
153
154
Provides result dictionary contribution for task results.
155
156
Attributes:
157
- result_contribution: Dictionary with unreachable=True
158
- omit_failed_key: Returns True to omit 'failed' from results
159
"""
160
161
class AnsibleAuthenticationFailure(AnsibleConnectionFailure):
162
"""
163
Invalid username/password/key.
164
165
Specialized connection failure for authentication problems.
166
"""
167
```
168
169
### Template Processing Errors
170
171
Errors encountered during Jinja2 template processing including syntax errors, undefined variables, and template security violations.
172
173
```python { .api }
174
class AnsibleTemplateError(AnsibleRuntimeError):
175
"""
176
A template related error.
177
178
Base class for all template processing errors.
179
"""
180
181
class AnsibleTemplateSyntaxError(AnsibleTemplateError):
182
"""
183
A syntax error was encountered while parsing a Jinja template or expression.
184
185
Wraps Jinja2 syntax errors with Ansible context.
186
"""
187
188
class AnsibleUndefinedVariable(AnsibleTemplateError):
189
"""
190
An undefined variable was encountered while processing a template or expression.
191
192
Raised when templates reference undefined variables.
193
"""
194
195
class TemplateTrustCheckFailedError(AnsibleTemplateError):
196
"""
197
Raised when processing was requested on an untrusted template or expression.
198
199
Security control for template processing from untrusted sources.
200
"""
201
202
class AnsibleBrokenConditionalError(AnsibleTemplateError):
203
"""
204
A broken conditional with non-boolean result was used.
205
206
Raised when conditional expressions don't evaluate to boolean values.
207
"""
208
209
class AnsibleTemplatePluginError(AnsibleTemplateError):
210
"""
211
An error sourced by a template plugin (lookup/filter/test).
212
213
Errors from template plugins like filters, tests, and lookups.
214
"""
215
```
216
217
### Action Flow Control Exceptions
218
219
Special exceptions used for controlling action plugin execution flow including skip conditions and early returns.
220
221
```python { .api }
222
class AnsibleAction(AnsibleRuntimeError):
223
"""
224
Base Exception for Action plugin flow control.
225
226
Provides result dictionary contribution for action results.
227
228
Parameters:
229
- result: Dictionary of result data
230
231
Attributes:
232
- result_contribution: Result data as mapping
233
- result: Mutable result dictionary for backward compatibility
234
"""
235
236
class AnsibleActionSkip(AnsibleAction):
237
"""
238
An action runtime skip.
239
240
Used to skip action execution with appropriate result marking.
241
242
Result contribution includes:
243
- skipped: True
244
- msg: Error message
245
"""
246
247
class AnsibleActionFail(AnsibleAction):
248
"""
249
An action runtime failure.
250
251
Used to fail action execution with appropriate result marking.
252
253
Result contribution includes:
254
- failed: True
255
- msg: Error message
256
"""
257
```
258
259
### Plugin System Errors
260
261
Errors related to the plugin system including missing plugins, circular redirects, and plugin loading failures.
262
263
```python { .api }
264
class AnsiblePluginError(AnsibleError):
265
"""
266
Base class for Ansible plugin-related errors that do not need AnsibleError contextual data.
267
268
Parameters:
269
- plugin_load_context: Context information about plugin loading
270
"""
271
272
class AnsiblePluginNotFound(AnsiblePluginError):
273
"""
274
Indicates we did not find an Ansible plugin.
275
276
Raised when requested plugins cannot be located or loaded.
277
"""
278
279
class AnsiblePluginRemovedError(AnsiblePluginError):
280
"""
281
A requested plugin has been removed.
282
283
Indicates deprecated plugins that have been removed from Ansible.
284
"""
285
286
class AnsiblePluginCircularRedirect(AnsiblePluginError):
287
"""
288
A cycle was detected in plugin redirection.
289
290
Prevents infinite loops in plugin alias chains.
291
"""
292
293
class AnsibleCollectionUnsupportedVersionError(AnsiblePluginError):
294
"""
295
A collection is not supported by this version of Ansible.
296
297
Version compatibility errors for collections.
298
"""
299
```
300
301
### File and Resource Errors
302
303
Errors related to file access, resource loading, and file system operations.
304
305
```python { .api }
306
class AnsibleFileNotFound(AnsibleRuntimeError):
307
"""
308
A file missing failure.
309
310
Enhanced file not found error with search path information.
311
312
Parameters:
313
- paths: List of paths searched for the file
314
- file_name: Name of the missing file
315
316
Provides detailed information about search locations.
317
"""
318
```
319
320
### Validation and Type Errors
321
322
Errors related to data validation, type checking, and variable storage constraints.
323
324
```python { .api }
325
class AnsibleTypeError(AnsibleRuntimeError, TypeError):
326
"""
327
Ansible-augmented TypeError subclass.
328
329
Enhanced type errors with Ansible context.
330
"""
331
332
class AnsibleVariableTypeError(AnsibleRuntimeError):
333
"""
334
An error due to attempted storage of an unsupported variable type.
335
336
Raised when variables contain unsupported data types.
337
"""
338
339
@classmethod
340
def from_value(cls, *, obj):
341
"""
342
Create type error from unsupported value.
343
344
Parameters:
345
- obj: The unsupported value
346
347
Returns:
348
AnsibleVariableTypeError: Configured error instance
349
"""
350
351
class AnsibleConditionalError(AnsibleRuntimeError):
352
"""
353
Errors related to failed conditional expression evaluation.
354
355
Raised when conditional expressions cannot be evaluated.
356
"""
357
```
358
359
### User Interaction Errors
360
361
Errors related to user prompts and interactive input handling.
362
363
```python { .api }
364
class AnsiblePromptInterrupt(AnsibleError):
365
"""
366
User interrupt.
367
368
Raised when user interrupts interactive prompts.
369
"""
370
371
class AnsiblePromptNoninteractive(AnsibleError):
372
"""
373
Unable to get user input.
374
375
Raised when interactive input is required but not available.
376
"""
377
```
378
379
## Error Handling Patterns
380
381
### Exception Context
382
All Ansible exceptions support source context through the `obj` parameter, which can contain origin information for precise error location reporting.
383
384
### Result Contribution
385
Some exceptions implement `ContributesToTaskResult` mixin to provide structured result data for task execution reporting.
386
387
### Error Message Formatting
388
Exceptions automatically format error messages with cause information unless disabled via `_include_cause_message = False`.
389
390
### Help Text
391
Exceptions can provide help text for error resolution through the `_help_text` attribute or constructor parameter.