ansible-pyhost 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1135 @@
1
+ """ansible-pyhost: run Ansible modules from Python.
2
+
3
+ Exposes typed ``AnsibleHost`` / ``AnsibleHosts`` / ``AnsibleLocalhost`` classes that
4
+ let you call Ansible modules as methods on host objects, batch tasks across an
5
+ inventory, and receive structured results as plain dicts.
6
+
7
+ Public API:
8
+
9
+ from ansible_pyhost import AnsibleHost, AnsibleHosts, AnsibleLocalhost
10
+
11
+ See the README for usage and compatibility notes.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import copy
17
+ import inspect
18
+ import json
19
+ import logging
20
+ import os
21
+ import warnings
22
+ from importlib.metadata import PackageNotFoundError
23
+ from importlib.metadata import version as _pkg_version
24
+ from typing import Any
25
+
26
+ import ansible
27
+ from ansible import constants as C
28
+ from ansible import context
29
+ from ansible.errors import AnsibleError
30
+ from ansible.executor.task_queue_manager import TaskQueueManager
31
+ from ansible.inventory.manager import InventoryManager
32
+ from ansible.module_utils.common.collections import ImmutableDict
33
+ from ansible.parsing.dataloader import DataLoader
34
+ from ansible.playbook.play import Play
35
+ from ansible.plugins.callback import CallbackBase
36
+ from ansible.plugins.loader import init_plugin_loader, module_loader
37
+ from ansible.utils.display import Display
38
+ from ansible.vars.hostvars import HostVars
39
+ from ansible.vars.manager import VariableManager
40
+
41
+ display = Display()
42
+ init_plugin_loader()
43
+
44
+ try:
45
+ __version__ = _pkg_version("ansible-pyhost")
46
+ except PackageNotFoundError:
47
+ # Source checkout without installed metadata (e.g., running from a tarball
48
+ # without ``pip install -e .``). Falls back to an inert marker.
49
+ __version__ = "0.0.0+unknown"
50
+
51
+ # Logger for the ansible-pyhost library. Users can configure verbosity by
52
+ # attaching handlers to this logger (logging.getLogger("ansible_pyhost")).
53
+ logger = logging.getLogger("ansible_pyhost")
54
+
55
+
56
+ def _resolve_log_verbosity() -> int:
57
+ """Return the library log verbosity, honoring the pre-rename env var."""
58
+ value = os.environ.get("ANSIBLE_PYHOST_VERBOSITY")
59
+ if value is None:
60
+ value = os.environ.get("ANSIBLE_HOST_VERBOSITY")
61
+ if value is not None:
62
+ warnings.warn(
63
+ "ANSIBLE_HOST_VERBOSITY is deprecated; "
64
+ "use ANSIBLE_PYHOST_VERBOSITY instead.",
65
+ DeprecationWarning,
66
+ stacklevel=3,
67
+ )
68
+ return int(value) if value is not None else 2
69
+
70
+
71
+ class _JsonResultsCallback(CallbackBase):
72
+ """Internal result collector for AnsibleHostsBase._run.
73
+
74
+ Not registered via Ansible's plugin loader: it is instantiated directly
75
+ by _run and attached to the TaskQueueManager's _callback_plugins list.
76
+ The leading underscore marks this as package-private; downstream users
77
+ should rely on the structured results returned by run_module() / .results
78
+ rather than instantiating this class themselves.
79
+
80
+ Derived from the json_results callback in sonic-net/sonic-mgmt (Apache 2.0).
81
+ """
82
+
83
+ CALLBACK_VERSION = 2.0
84
+ # Deliberately NOT 'stdout' — Ansible's built-in `null` stdout callback
85
+ # handles terminal output (silently); this collector is purely a result sink.
86
+ CALLBACK_TYPE = "notification"
87
+ CALLBACK_NAME = "ansible_pyhost._json_results"
88
+
89
+ TASK_FIELDS = (
90
+ "action",
91
+ "become",
92
+ "become_method",
93
+ "become_user",
94
+ "connection",
95
+ "ignore_errors",
96
+ "ignore_unreachable",
97
+ "register",
98
+ "retries",
99
+ "timeout",
100
+ )
101
+
102
+ def __init__(self):
103
+ super().__init__()
104
+ self._results: dict[str, list[dict]] = {}
105
+
106
+ def _get_module_name(self, result):
107
+ if ansible.__version__ >= "2.19.0":
108
+ return result.task
109
+ return result.task_name
110
+
111
+ def _get_task_fields(self, result):
112
+ return {
113
+ field: result._task_fields[field]
114
+ for field in self.TASK_FIELDS
115
+ if field in result._task_fields
116
+ }
117
+
118
+ def _log_res(self, hostname, module_name, res):
119
+ if display.verbosity == 0:
120
+ return
121
+ if display.verbosity == 1:
122
+ log_func = display.v
123
+ brief = json.dumps(
124
+ {"module_name": module_name, "reachable": res["reachable"], "failed": res["failed"]},
125
+ default=str,
126
+ )
127
+ msg = f"[{hostname}] => {brief}"
128
+ elif display.verbosity == 2:
129
+ log_func = display.vv
130
+ msg = f"[{hostname}] => {json.dumps(res, default=str)}"
131
+ elif display.verbosity == 3:
132
+ log_func = display.vvv
133
+ msg = f"[{hostname}] => {json.dumps(res, indent=4, default=str)}"
134
+ else:
135
+ log_func = display.vvvv
136
+ msg = f"[{hostname}] => {json.dumps(res, indent=4, default=str)}"
137
+ log_func(msg)
138
+
139
+ def _record(self, result, *, reachable, failed):
140
+ hostname = str(result._host.get_name())
141
+ module_name = self._get_module_name(result)
142
+ self._results.setdefault(hostname, [])
143
+ res = dict(hostname=hostname, reachable=reachable, failed=failed)
144
+ # deepcopy preserves non-serializable values (e.g. Task instances in
145
+ # _task_fields on ansible-core 2.19+); the prior json round-trip lost
146
+ # or crashed on those.
147
+ res.update(copy.deepcopy(result._result))
148
+ if "invocation" in res and isinstance(res["invocation"], dict):
149
+ res["invocation"]["module_name"] = module_name
150
+ res["_task_fields"] = self._get_task_fields(result)
151
+ self._log_res(hostname, module_name, res)
152
+ self._results[hostname].append(res)
153
+
154
+ def v2_runner_on_ok(self, result):
155
+ self._record(result, reachable=True, failed=False)
156
+
157
+ def v2_runner_on_failed(self, result, *args, **kwargs):
158
+ self._record(result, reachable=True, failed=True)
159
+
160
+ def v2_runner_on_unreachable(self, result):
161
+ self._record(result, reachable=False, failed=True)
162
+
163
+ @property
164
+ def results(self) -> dict[str, list[dict]]:
165
+ return self._results
166
+
167
+
168
+ def _to_native_type(value: Any) -> Any:
169
+ """Convert Ansible types (AnsibleUnicode, AnsibleUnsafeText, etc.) to native Python types.
170
+
171
+ Args:
172
+ value: Value to convert
173
+
174
+ Returns:
175
+ Native Python type (str, list, dict, etc.)
176
+ """
177
+ # Check if value has the Ansible unicode/text types
178
+ if hasattr(value, '__class__') and value.__class__.__name__ in ('AnsibleUnicode', 'AnsibleUnsafeText'):
179
+ return str(value)
180
+ elif isinstance(value, dict):
181
+ return {k: _to_native_type(v) for k, v in value.items()}
182
+ elif isinstance(value, list):
183
+ return [_to_native_type(item) for item in value]
184
+ else:
185
+ return value
186
+
187
+
188
+ class UnsupportedAnsibleModule(AnsibleError):
189
+ pass
190
+
191
+
192
+ class NoAnsibleHostError(AnsibleError):
193
+ pass
194
+
195
+
196
+ class MultipleAnsibleHostsError(AnsibleError):
197
+ pass
198
+
199
+
200
+ class NoTasksError(AnsibleError):
201
+ pass
202
+
203
+
204
+ class AnsibleModuleFailed(AnsibleError):
205
+ pass
206
+
207
+
208
+ class AnsibleHostsBase:
209
+
210
+ def __init__(
211
+ self,
212
+ inventory: str | list[str],
213
+ pattern: str,
214
+ hostvars: dict[str, Any] | None = None,
215
+ options: dict[str, Any] | None = None
216
+ ) -> None:
217
+
218
+ hostvars = hostvars or {}
219
+ options = options or {}
220
+
221
+ self.inventory = inventory
222
+ self.pattern = pattern
223
+ self._extra_hostvars = hostvars
224
+
225
+ if pattern != 'localhost':
226
+ inventory_files = inventory if isinstance(inventory, list) else [inventory]
227
+ for inv_file in inventory_files:
228
+ if not os.path.exists(inv_file):
229
+ raise AnsibleError(f"Inventory file does not exist: {inv_file}")
230
+
231
+ self.loader = DataLoader()
232
+ self.im = InventoryManager(loader=self.loader, sources=self.inventory)
233
+
234
+ # Ansible inventory hosts: list of <class 'ansible.inventory.host.Host'>
235
+ self.ans_inv_hosts = self.im.get_hosts(self.pattern)
236
+ self.hostnames = [host.name for host in self.ans_inv_hosts]
237
+ self.hosts_count = len(self.hostnames)
238
+ self.ips = [host.get_vars().get("ansible_host", None) for host in self.ans_inv_hosts]
239
+ self.v4ips = self.ips
240
+ self.v6ips = [host.get_vars().get("ansible_hostv6", None) for host in self.ans_inv_hosts]
241
+
242
+ self.vm = VariableManager(loader=self.loader, inventory=self.im)
243
+
244
+ # Ansible's load_extra_vars() memoizes its result and VariableManager
245
+ # stores it by reference, so mutating vm.extra_vars in place (via the
246
+ # hostvars= path below or update_extra_vars) would leak into every other
247
+ # VariableManager in the process. Give this instance its own copy.
248
+ self.vm._extra_vars = dict(self.vm._extra_vars)
249
+
250
+ # Use C.XXXX, so that defaults are consistent with ansible.cfg, can be overridden by env vars
251
+ self.options = {
252
+ "forks": C.DEFAULT_FORKS,
253
+ "connection": C.DEFAULT_TRANSPORT,
254
+ "timeout": C.DEFAULT_TIMEOUT,
255
+ "task_timeout": C.TASK_TIMEOUT,
256
+ "become": C.DEFAULT_BECOME,
257
+ "become_method": C.DEFAULT_BECOME_METHOD
258
+ }
259
+ if options:
260
+ self.options.update(options)
261
+
262
+ # Trigger ansible to load and render host variables in case host variables are defined as Jinja2 templates.
263
+ # After this operation, self.vm._hostvars will be populated with content
264
+ # self.vm._hostvars["example_hostname"] will return all variables visible by "example_hostname"
265
+ # The best part is that if the variable is a template, it is automatically rendered with correct data type
266
+ HostVars(inventory=self.im, variable_manager=self.vm, loader=self.loader)
267
+
268
+ if hostvars:
269
+ self.vm.extra_vars.update(hostvars)
270
+
271
+ self._loaded_modules: list[dict] = []
272
+ self._batch_mode: bool = False
273
+ self._batch_results: dict = {}
274
+
275
+ @staticmethod
276
+ def _get_caller_info(stack_depth: int = 2) -> tuple[str, int]:
277
+ """Get filename and line number of the caller.
278
+
279
+ Args:
280
+ stack_depth: How many levels up the stack to look (default 2)
281
+ Higher values go further up the call stack
282
+
283
+ Returns:
284
+ tuple: (filename, line_number) of the caller
285
+ """
286
+ frame = inspect.currentframe()
287
+ try:
288
+ # Go up the stack to find the actual caller
289
+ for _ in range(stack_depth):
290
+ frame = frame.f_back
291
+ if frame is None:
292
+ return "unknown", 0
293
+
294
+ frameinfo = inspect.getframeinfo(frame)
295
+ return frameinfo.filename, frameinfo.lineno
296
+ finally:
297
+ del frame # Avoid reference cycles
298
+
299
+ @staticmethod
300
+ def _validate_module_name(module_name: str) -> None:
301
+ # Check if 'module_name' is a valid Ansible module
302
+ _module = module_loader.find_plugin_with_context(module_name)
303
+
304
+ if not _module.resolved:
305
+ searched_paths = module_loader.print_paths()
306
+ raise UnsupportedAnsibleModule(
307
+ f"\n"
308
+ f" Ansible module '{module_name}' is not supported or could not be found.\n"
309
+ f' Searched paths: {searched_paths}\n'
310
+ f' Please ensure that ANSIBLE_LIBRARY is properly configured.\n'
311
+ f' Ref: https://docs.ansible.com/ansible/latest/reference_appendices/'
312
+ f'config.html#envvar-ANSIBLE_LIBRARY'
313
+ )
314
+
315
+ @staticmethod
316
+ def build_task(
317
+ module_name: str,
318
+ args: list | None = None,
319
+ kwargs: dict | None = None,
320
+ task_directives: dict | None = None
321
+ ) -> dict:
322
+
323
+ args = args or []
324
+ kwargs = kwargs or {}
325
+ task_directives = task_directives or {}
326
+
327
+ # Validate module name first
328
+ AnsibleHostsBase._validate_module_name(module_name)
329
+
330
+ kwargs = copy.deepcopy(kwargs) # Copy to avoid argument passed by reference issue
331
+ if args:
332
+ kwargs["_raw_params"] = " ".join(args)
333
+
334
+ # Support the "module_ignore_errors" kwarg added in the legacy class for backward compatibility
335
+ _module_ignore_errors = False
336
+ if 'module_ignore_errors' in kwargs:
337
+ _module_ignore_errors = kwargs.pop('module_ignore_errors')
338
+
339
+ task_data = {
340
+ "action": {
341
+ "module": module_name,
342
+ "args": kwargs
343
+ },
344
+ }
345
+ # Intentional identity check (not truthy, not ==): only the literal bool
346
+ # True opts in. `==` would wrongly accept 1/1.0 because `1 == True` is
347
+ # True in Python; `is True` rejects every non-bool value.
348
+ if _module_ignore_errors is True:
349
+ # It could be overwritten by the 'ignore_errors' in task_directives if both are provided.
350
+ # This is to encourage the using of formal 'ignore_errors' attribute.
351
+ task_data['ignore_errors'] = True
352
+
353
+ if task_directives:
354
+ task_data.update(task_directives)
355
+
356
+ return task_data
357
+
358
+ def _check_failed_results(self, results):
359
+ failed_results = []
360
+ if isinstance(self, AnsibleHost) or isinstance(self, AnsibleLocalhost):
361
+ # Single host
362
+ if isinstance(results, dict):
363
+ # Single task
364
+ if results.get('failed', False):
365
+ if not results.get('_task_fields', {}).get('ignore_errors', False):
366
+ failed_results.append(results)
367
+ elif isinstance(results, list):
368
+ # Multiple tasks
369
+ for res in results:
370
+ if res.get('failed', False):
371
+ if not res.get('_task_fields', {}).get('ignore_errors', False):
372
+ failed_results.append(res)
373
+ elif isinstance(self, AnsibleHosts):
374
+ # Multiple hosts
375
+ if isinstance(results, dict):
376
+ # Multiple hosts, multiple tasks
377
+ for hostname in results:
378
+ host_results = results[hostname]
379
+ if isinstance(host_results, dict):
380
+ # Single task
381
+ if host_results.get('failed', False):
382
+ if not host_results.get('_task_fields', {}).get('ignore_errors', False):
383
+ failed_results.append(host_results)
384
+ elif isinstance(host_results, list):
385
+ # Multiple tasks
386
+ for res in host_results:
387
+ if res.get('failed', False):
388
+ if not res.get('_task_fields', {}).get('ignore_errors', False):
389
+ failed_results.append(res)
390
+
391
+ if failed_results:
392
+ raise AnsibleModuleFailed(
393
+ f"Ansible module failed. If failure is expected, use `task_directives={{'ignore_errors': True}}` "
394
+ f"to avoid raising an exception. Details: "
395
+ f"{json.dumps(failed_results, indent=4, default=str)}"
396
+ )
397
+
398
+ def _run(
399
+ self,
400
+ tasks: list[dict] | None = None,
401
+ options: dict[str, Any] | None = None,
402
+ gather_facts: bool = False
403
+ ) -> dict | list[dict]:
404
+ tasks = tasks or []
405
+ options = options or {}
406
+
407
+ # Validate tasks list
408
+ if not tasks or len(tasks) == 0:
409
+ raise NoTasksError("No tasks provided to execute")
410
+
411
+ tqm = None
412
+ try:
413
+ _options = copy.deepcopy(self.options)
414
+ _options.update(options)
415
+
416
+ # According to the above logic, `verbosity` from `self._run` will overwrite the one from `self.__init__`.
417
+ log_verbosity = _options.pop('verbosity', None)
418
+ if log_verbosity is None:
419
+ log_verbosity = _resolve_log_verbosity()
420
+
421
+ # NOTE: ``ansible.context`` holds a process-global CLI context. This call
422
+ # mutates it for the entire process. Two ``AnsibleHosts`` instances running
423
+ # concurrently in different threads with different options will race on
424
+ # this state. The library is currently designed for sequential use; for
425
+ # concurrent execution, prefer Ansible's own forking via ``forks=`` over
426
+ # threading multiple instances.
427
+ context._init_global_context(ImmutableDict(**_options))
428
+
429
+ # Get caller information for logging
430
+ caller_file, caller_line = self._get_caller_info(stack_depth=3)
431
+ caller_file_base = os.path.basename(caller_file)
432
+ if logger.isEnabledFor(logging.DEBUG) and log_verbosity > 0:
433
+ for task in tasks:
434
+ # To honor the ansible's no_log attribute
435
+ # Ref: https://docs.ansible.com/ansible/latest/reference_appendices/
436
+ # logging.html#protecting-sensitive-data-with-no-log
437
+ no_log = task.get('no_log', False)
438
+
439
+ module_name = task['action']['module']
440
+ log_prefix = f'{caller_file_base}:{caller_line} >> {self.hostnames} =>'
441
+ if log_verbosity == 1:
442
+ if no_log:
443
+ log_details = '[no_log]'
444
+ else:
445
+ log_details = f'{module_name}'
446
+ elif log_verbosity >= 2:
447
+ if no_log:
448
+ log_details = '[no_log]'
449
+ else:
450
+ args = task['action'].get('args', {}).get('_raw_params', '').split(' ')
451
+ kwargs = {k: v for k, v in task['action'].get('args', {}).items() if k != '_raw_params'}
452
+ task_directives = {k: v for k, v in task.items() if k != 'action'}
453
+ log_details = (
454
+ f'{module_name}, args={json.dumps(args, default=str)}, '
455
+ f'kwargs={json.dumps(kwargs, default=str)}, '
456
+ f'task_directives={json.dumps(task_directives, default=str)}'
457
+ )
458
+ logger.debug(f'{log_prefix} {log_details}')
459
+
460
+ # The ansible logging level is not determined by the `verbosity` value in options.
461
+ # Set ansible logging level according to 'verbosity' configuration in ansible.cfg
462
+ # or by ANSIBLE_VERBOSITY env var.
463
+ # Ref: https://docs.ansible.com/projects/ansible/latest/reference_appendices/config.html#default-verbosity
464
+ _original_display_verbosity = display.verbosity
465
+ display.verbosity = C.DEFAULT_VERBOSITY
466
+
467
+ play = Play().load(
468
+ {
469
+ "hosts": self.pattern,
470
+ "gather_facts": gather_facts,
471
+ "become_method": _options.get('become_method', 'sudo'),
472
+ "connection": _options.get('connection', 'smart'),
473
+ "ignore_errors": _options.get('ignore_errors', False),
474
+ "tasks": tasks
475
+ },
476
+ variable_manager=self.vm,
477
+ loader=self.loader
478
+ )
479
+ # TQM requires a registered stdout callback name to satisfy
480
+ # load_callbacks(); we pass 'minimal' (one of Ansible's built-ins)
481
+ # then evict it from _callback_plugins before run() so nothing
482
+ # prints to stdout. Our own _JsonResultsCallback is attached as
483
+ # the sole receiver of task events.
484
+ if ansible.__version__ >= '2.19.0':
485
+ tqm = TaskQueueManager(
486
+ inventory=self.im,
487
+ variable_manager=self.vm,
488
+ loader=self.loader,
489
+ passwords={},
490
+ stdout_callback_name='minimal',
491
+ run_tree=False,
492
+ forks=self.options.get("forks")
493
+ )
494
+ else:
495
+ tqm = TaskQueueManager(
496
+ inventory=self.im,
497
+ variable_manager=self.vm,
498
+ loader=self.loader,
499
+ passwords={},
500
+ stdout_callback='minimal',
501
+ run_tree=False,
502
+ forks=self.options.get("forks")
503
+ )
504
+ tqm.load_callbacks()
505
+
506
+ # Remove the built-in stdout callback (suppresses terminal output)
507
+ # and attach our explicit result collector in its place.
508
+ tqm._callback_plugins[:] = [
509
+ cb for cb in tqm._callback_plugins
510
+ if getattr(cb, 'CALLBACK_TYPE', None) != 'stdout'
511
+ ]
512
+ results_collector = _JsonResultsCallback()
513
+ # _init_callback_methods populates _implemented_callback_methods,
514
+ # which TQM.send_callback gates dispatch on. The plugin loader calls
515
+ # this implicitly when loading callbacks via the loader; since we
516
+ # construct our collector directly, we have to invoke it ourselves.
517
+ if hasattr(results_collector, '_init_callback_methods'):
518
+ results_collector._init_callback_methods()
519
+ tqm._callback_plugins.append(results_collector)
520
+
521
+ tqm.run(play)
522
+
523
+ results = results_collector.results
524
+
525
+ # results is a dict: {hostname: [task_result_dict, ...], ...}
526
+ # It makes sense to return this format of results for multiple hosts and multiple tasks
527
+ # However, for single host or single task scenarios, we can simplify the results structure
528
+ # Simplify results based on number of tasks
529
+ if len(tasks) == 1: # This means single task, but could still be multiple hosts
530
+ # Single task, results is a list of dict with single item. Convert to single dict per host
531
+ for hostname in results:
532
+ if isinstance(results[hostname], list) and len(results[hostname]) == 1:
533
+ results[hostname] = results[hostname][0]
534
+
535
+ # For single host scenarios, return just the single host's result without hostname key
536
+ if isinstance(self, AnsibleHost) or isinstance(self, AnsibleLocalhost):
537
+ results = results[self.hostname]
538
+
539
+ _tqm_stats = {
540
+ 'processed': tqm._stats.processed,
541
+ 'failures': tqm._stats.failures,
542
+ 'ok': tqm._stats.ok,
543
+ 'unreachable': tqm._stats.dark,
544
+ 'changed': tqm._stats.changed,
545
+ 'skipped': tqm._stats.skipped,
546
+ 'rescued': tqm._stats.rescued,
547
+ 'ignored': tqm._stats.ignored,
548
+ }
549
+
550
+ if logger.isEnabledFor(logging.DEBUG) and log_verbosity > 0:
551
+ if log_verbosity == 1:
552
+ logger.debug(f'{caller_file}:{caller_line} >> {self.hostnames} => done')
553
+ elif log_verbosity == 2:
554
+ logger.debug(
555
+ f'{caller_file}:{caller_line} >> {self.hostnames} => '
556
+ f'{json.dumps(results, default=str)}'
557
+ )
558
+ elif log_verbosity >= 3:
559
+ logger.debug(
560
+ f'{caller_file}:{caller_line} >> {self.hostnames} => '
561
+ f'{json.dumps(results, indent=4, default=str)}'
562
+ )
563
+ if log_verbosity >= 4:
564
+ logger.debug(
565
+ f'{caller_file}:{caller_line} >> TaskQueueManager Stats: '
566
+ f'{json.dumps(_tqm_stats, indent=4, default=str)}'
567
+ )
568
+
569
+ finally:
570
+ if tqm:
571
+ tqm.cleanup()
572
+ self.loader.cleanup_all_tmp_files()
573
+ display.verbosity = _original_display_verbosity
574
+
575
+ self._check_failed_results(results)
576
+
577
+ return results
578
+
579
+ def run_module(
580
+ self,
581
+ module_name: str,
582
+ args: list | None = None,
583
+ kwargs: dict | None = None,
584
+ task_directives: dict | None = None,
585
+ options: dict | None = None,
586
+ gather_facts: bool = False
587
+ ) -> dict | list[dict] | None:
588
+
589
+ args = args or []
590
+ kwargs = kwargs or {}
591
+ task_directives = task_directives or {}
592
+ options = options or {}
593
+
594
+ task = self.build_task(
595
+ module_name=module_name,
596
+ args=args,
597
+ kwargs=kwargs,
598
+ task_directives=task_directives
599
+ )
600
+
601
+ if self._batch_mode:
602
+ # In batch mode the task is queued; execution is deferred to context-manager exit.
603
+ self._loaded_modules.append(task)
604
+ return None
605
+
606
+ try:
607
+ results = self._run(tasks=[task], options=options, gather_facts=gather_facts)
608
+ except Exception as e:
609
+ if isinstance(args, str):
610
+ raise type(e)(
611
+ f"{str(e)}\n"
612
+ f"Note: 'args' parameter must be a list, not a string. "
613
+ f"You passed args='{args}' (string). Use args=['{args}'] instead."
614
+ ) from e
615
+ else:
616
+ raise
617
+
618
+ return results
619
+
620
+ def load_module(
621
+ self,
622
+ module_name: str,
623
+ args: list | None = None,
624
+ kwargs: dict | None = None,
625
+ task_directives: dict | None = None
626
+ ) -> None:
627
+ task = self.build_task(
628
+ module_name=module_name,
629
+ args=args or [],
630
+ kwargs=kwargs or {},
631
+ task_directives=task_directives or {}
632
+ )
633
+ self._loaded_modules.append(task)
634
+
635
+ def run_loaded_modules(
636
+ self,
637
+ options: dict[str, Any] | None = None,
638
+ gather_facts: bool = False
639
+ ) -> dict | list[dict]:
640
+ options = options or {}
641
+ try:
642
+ if len(self._loaded_modules) == 0:
643
+ return {}
644
+ results = self._run(tasks=self._loaded_modules, options=options, gather_facts=gather_facts)
645
+ finally:
646
+ self._loaded_modules = []
647
+
648
+ return results
649
+
650
+ def __getattr__(self, name: str) -> callable:
651
+ # Don't intercept dunder attribute lookups: Python's machinery (copy, pickle,
652
+ # repr, debuggers, etc.) probes for things like __deepcopy__, __getstate__,
653
+ # __wrapped__. Treating those as Ansible module names produces confusing
654
+ # UnsupportedAnsibleModule errors. Let normal AttributeError be raised so
655
+ # callers can fall back to default behavior.
656
+ if name.startswith('__') and name.endswith('__'):
657
+ raise AttributeError(
658
+ f"{type(self).__name__!r} object has no attribute {name!r}"
659
+ )
660
+
661
+ def _run_ansible_module(
662
+ *args,
663
+ task_directives: dict | None = None,
664
+ options: dict | None = None,
665
+ gather_facts: bool = False,
666
+ **kwargs
667
+ ) -> dict | list[dict] | None:
668
+ task = self.build_task(
669
+ module_name=name,
670
+ args=list(args),
671
+ kwargs=kwargs,
672
+ task_directives=task_directives or {}
673
+ )
674
+ if self._batch_mode:
675
+ self._loaded_modules.append(task)
676
+ # `options` and `gather_facts` are ignored in batch mode.
677
+ # Module is not executed immediately, so no results to return.
678
+ # Loaded modules will be executed when context manager exits.
679
+ return None
680
+ return self._run(tasks=[task], options=options or {}, gather_facts=gather_facts)
681
+
682
+ return _run_ansible_module
683
+
684
+ def __enter__(self) -> AnsibleHostsBase:
685
+ self._batch_mode = True
686
+ self._loaded_modules = []
687
+ self._batch_results = {}
688
+ logger.debug("===== Entering AnsibleHostsBase context manager for batch module execution. =====")
689
+ return self
690
+
691
+ def __exit__(self, exc_type, exc_val, exc_tb) -> None:
692
+ try:
693
+ self._batch_results = self._run(tasks=self._loaded_modules)
694
+ finally:
695
+ self._batch_mode = False
696
+ self._loaded_modules = []
697
+ logger.debug(
698
+ "===== Exiting AnsibleHostsBase context manager after batch module execution. "
699
+ "Access results via 'results' property of the instance. ====="
700
+ )
701
+
702
+ @property
703
+ def results(self) -> dict:
704
+ '''Returns the results tasks executed in context.
705
+
706
+ Clears the stored results after returning them to avoid stale data on subsequent calls.
707
+ '''
708
+ _batch_results = self._batch_results
709
+ self._batch_results = {}
710
+ return _batch_results
711
+
712
+ def _get_host_vars_dict(self, hostname: str) -> dict[str, Any]:
713
+ """Get all variables directly defined for a specific host.
714
+
715
+ Returns only variables from host_vars/, not group_vars or other sources.
716
+
717
+ Args:
718
+ hostname: Name of the host to get variables for
719
+
720
+ Returns:
721
+ Dictionary of variables directly defined for this host
722
+
723
+ Raises:
724
+ KeyError: If hostname is not in the matched hosts
725
+ """
726
+ if hostname not in self.hostnames:
727
+ raise KeyError(f"Host '{hostname}' not found in matched hosts: {self.hostnames}")
728
+
729
+ # Get the inventory host object
730
+ inv_host = None
731
+ for host in self.ans_inv_hosts:
732
+ if host.name == hostname:
733
+ inv_host = host
734
+ break
735
+
736
+ # Get host-specific variables (not group vars)
737
+ return inv_host.get_vars() if inv_host else {}
738
+
739
+ def get_host_var(self, hostname: str, var_name: str, default: Any = None) -> Any:
740
+ """Get a specific variable directly defined for a host.
741
+
742
+ Returns only variables from host_vars/, not group_vars or other sources.
743
+
744
+ Args:
745
+ hostname: Name of the host to get variable for
746
+ var_name: Variable name to retrieve
747
+ default: Default value to return if variable is not found
748
+
749
+ Returns:
750
+ Value of the specific variable, or default if not found
751
+
752
+ Raises:
753
+ KeyError: If hostname is not in the matched hosts
754
+ """
755
+ host_vars_dict = self._get_host_vars_dict(hostname)
756
+ value = host_vars_dict.get(var_name, default)
757
+ return _to_native_type(value)
758
+
759
+ def _get_visible_vars_dict(self, hostname: str) -> dict[str, Any]:
760
+ """Get all variables visible to a specific host.
761
+
762
+ Includes host_vars, group_vars, inventory vars, extra_vars.
763
+ Jinja2 templates are automatically rendered.
764
+
765
+ Args:
766
+ hostname: Name of the host to get variables for
767
+
768
+ Returns:
769
+ Dictionary of all variables visible to this host (computed/resolved)
770
+
771
+ Raises:
772
+ KeyError: If hostname is not in the matched hosts
773
+ """
774
+ if hostname not in self.hostnames:
775
+ raise KeyError(f"Host '{hostname}' not found in matched hosts: {self.hostnames}")
776
+
777
+ # Use VariableManager's _hostvars which contains all variables
778
+ # including group vars, inventory vars, and extra vars
779
+ # Templates are automatically rendered
780
+ return dict(self.vm._hostvars[hostname])
781
+
782
+ def get_visible_var(self, hostname: str, var_name: str, default: Any = None) -> Any:
783
+ """Get a specific variable visible to a host.
784
+
785
+ Includes host_vars, group_vars, inventory vars, extra_vars.
786
+ Jinja2 templates are automatically rendered.
787
+
788
+ Args:
789
+ hostname: Name of the host to get variable for
790
+ var_name: Variable name to retrieve
791
+ default: Default value to return if variable is not found
792
+
793
+ Returns:
794
+ Value of the specific variable, or default if not found
795
+
796
+ Raises:
797
+ KeyError: If hostname is not in the matched hosts
798
+ """
799
+ visible_vars_dict = self._get_visible_vars_dict(hostname)
800
+ value = visible_vars_dict.get(var_name, default)
801
+ return _to_native_type(value)
802
+
803
+ @property
804
+ def extra_vars(self) -> dict[str, Any]:
805
+ """Get extra variables.
806
+
807
+ Returns:
808
+ Dictionary of extra variables
809
+ """
810
+ return self.vm.extra_vars
811
+
812
+
813
+ class AnsibleHosts(AnsibleHostsBase):
814
+ """Subclass for working with multiple Ansible hosts.
815
+
816
+ Supports container-like operations:
817
+ - Indexing: hosts[0] or hosts['hostname']
818
+ - Iteration: for host in hosts:
819
+ - Length: len(hosts)
820
+ """
821
+
822
+ def __init__(
823
+ self,
824
+ inventory: str | list[str],
825
+ pattern: str,
826
+ hostvars: dict[str, Any] | None = None,
827
+ options: dict[str, Any] | None = None
828
+ ) -> None:
829
+ super().__init__(inventory, pattern, hostvars, options)
830
+
831
+ # Validate that at least one host matches the 'pattern'
832
+ if self.hosts_count == 0:
833
+ raise NoAnsibleHostError(
834
+ f"No host '{self.pattern}' in inventory '{self.inventory}'"
835
+ )
836
+
837
+ def _make_single_host(self, hostname: str) -> AnsibleHost:
838
+ """Build an ``AnsibleHost`` for ``hostname`` reusing this group's parsed inventory.
839
+
840
+ The naive path of constructing ``AnsibleHost(inventory, hostname, ...)`` re-parses
841
+ the inventory and re-renders host variables on every call, which is O(N) per
842
+ access on a group of N hosts. This helper bypasses the re-parse by sharing
843
+ ``self.loader``, ``self.im`` and ``self.vm`` with the new instance.
844
+ """
845
+ host = AnsibleHost.__new__(AnsibleHost)
846
+ # AnsibleHostsBase fields
847
+ host.inventory = self.inventory
848
+ host.pattern = hostname
849
+ host._extra_hostvars = self._extra_hostvars
850
+ host.loader = self.loader
851
+ host.im = self.im
852
+ host.vm = self.vm
853
+ ans_hosts = [h for h in self.ans_inv_hosts if h.name == hostname]
854
+ if not ans_hosts:
855
+ raise NoAnsibleHostError(
856
+ f"Host '{hostname}' is not part of pattern '{self.pattern}'"
857
+ )
858
+ host.ans_inv_hosts = ans_hosts
859
+ host.hostnames = [hostname]
860
+ host.hosts_count = 1
861
+ host.ips = [ans_hosts[0].get_vars().get("ansible_host", None)]
862
+ host.v4ips = host.ips
863
+ host.v6ips = [ans_hosts[0].get_vars().get("ansible_hostv6", None)]
864
+ host.options = dict(self.options)
865
+ host._loaded_modules = []
866
+ host._batch_mode = False
867
+ host._batch_results = {}
868
+ # AnsibleHost-specific singular convenience fields
869
+ host.hostname = hostname
870
+ host.ip = host.ips[0]
871
+ host.v4ip = host.v4ips[0]
872
+ host.v6ip = host.v6ips[0]
873
+ return host
874
+
875
+ def __getitem__(self, key: int | str) -> AnsibleHost:
876
+ """Support both integer and string indexing.
877
+
878
+ Args:
879
+ key: Integer index (0-based) or hostname string
880
+
881
+ Returns:
882
+ AnsibleHost instance for the specified host
883
+
884
+ Examples:
885
+ hosts[0] # First host by integer index
886
+ hosts['vlab-01'] # Host by hostname
887
+ """
888
+ if isinstance(key, int):
889
+ # Integer indexing
890
+ if key < 0 or key >= len(self.hostnames):
891
+ raise IndexError(f"Index {key} out of range for {len(self.hostnames)} hosts")
892
+ hostname = self.hostnames[key]
893
+ elif isinstance(key, str):
894
+ # String indexing by hostname
895
+ if key not in self.hostnames:
896
+ raise KeyError(f"Host '{key}' not found in matched hosts: {self.hostnames}")
897
+ hostname = key
898
+ else:
899
+ raise TypeError(f"Indices must be integers or strings, not {type(key).__name__}")
900
+
901
+ return self._make_single_host(hostname)
902
+
903
+ def __iter__(self):
904
+ """Support iteration over hosts.
905
+
906
+ Yields:
907
+ AnsibleHost instances for each host
908
+
909
+ Example:
910
+ for host in hosts:
911
+ print(host.hostname)
912
+ """
913
+ for hostname in self.hostnames:
914
+ yield self._make_single_host(hostname)
915
+
916
+ def __len__(self) -> int:
917
+ """Return the number of hosts.
918
+
919
+ Returns:
920
+ Number of hosts matched by the 'pattern'
921
+
922
+ Example:
923
+ len(hosts) # Returns count of matched hosts
924
+ """
925
+ return self.hosts_count
926
+
927
+ def __str__(self) -> str:
928
+ """Return a user-friendly string representation."""
929
+ return f"AnsibleHosts(pattern='{self.pattern}', hostnames={self.hostnames})"
930
+
931
+ def __repr__(self) -> str:
932
+ """Return a detailed string representation for debugging."""
933
+ inv_str = self.inventory if isinstance(self.inventory, str) else f"[{', '.join(self.inventory)}]"
934
+ return f"AnsibleHosts(inventory={inv_str}, pattern='{self.pattern}', hostnames={self.hostnames})"
935
+
936
+
937
+ class AnsibleHost(AnsibleHostsBase):
938
+ """Subclass for working with a single Ansible host."""
939
+
940
+ def __init__(
941
+ self,
942
+ inventory: str | list[str],
943
+ pattern: str,
944
+ hostvars: dict[str, Any] | None = None,
945
+ options: dict[str, Any] | None = None
946
+ ) -> None:
947
+ super().__init__(inventory, pattern, hostvars, options)
948
+ # Validate that exactly one host matches the 'pattern'
949
+ if self.hosts_count == 0:
950
+ raise NoAnsibleHostError(
951
+ f"No host '{self.pattern}' in inventory '{self.inventory}'"
952
+ )
953
+ elif self.hosts_count > 1:
954
+ raise MultipleAnsibleHostsError(
955
+ f"Expected exactly one host, but '{self.pattern}' matched {self.hosts_count} hosts "
956
+ f"in inventory '{self.inventory}': {self.hostnames}"
957
+ )
958
+
959
+ # Add singular attributes for single host access
960
+ self.hostname = self.hostnames[0]
961
+ self.ip = self.ips[0]
962
+ self.v4ip = self.v4ips[0]
963
+ self.v6ip = self.v6ips[0]
964
+
965
+ def get_host_var(self, var_name: str, default: Any = None) -> Any:
966
+ """Get a specific variable directly defined for this host.
967
+
968
+ Returns only variables from host_vars/, not group_vars or other sources.
969
+
970
+ Args:
971
+ var_name: Variable name to retrieve
972
+ default: Default value to return if variable is not found
973
+
974
+ Returns:
975
+ Value of the specific variable, or default if not found
976
+ """
977
+ return super().get_host_var(self.hostname, var_name, default)
978
+
979
+ def get_visible_var(self, var_name: str, default: Any = None) -> Any:
980
+ """Get a specific variable visible to this host.
981
+
982
+ Includes host_vars, group_vars, inventory vars, extra_vars.
983
+ Jinja2 templates are automatically rendered.
984
+
985
+ Args:
986
+ var_name: Variable name to retrieve
987
+ default: Default value to return if variable is not found
988
+
989
+ Returns:
990
+ Value of the specific variable, or default if not found
991
+ """
992
+ return super().get_visible_var(self.hostname, var_name, default)
993
+
994
+ def update_extra_vars(self, extra_vars: dict[str, Any]) -> None:
995
+ """Update extra variables for this host.
996
+
997
+ Args:
998
+ extra_vars: Dictionary of variables to add/update in extra_vars
999
+ """
1000
+ self.vm.extra_vars.update(extra_vars)
1001
+
1002
+ @property
1003
+ def host_vars(self) -> dict[str, Any]:
1004
+ """Variables directly defined for this host (convenience property).
1005
+
1006
+ Returns:
1007
+ Dictionary of variables directly defined for this host
1008
+ """
1009
+ return super()._get_host_vars_dict(self.hostname)
1010
+
1011
+ @property
1012
+ def visible_vars(self) -> dict[str, Any]:
1013
+ """All variables visible to this host (convenience property).
1014
+
1015
+ Returns:
1016
+ Dictionary of all variables visible to this host (computed/resolved)
1017
+ """
1018
+ return super()._get_visible_vars_dict(self.hostname)
1019
+
1020
+ def __str__(self) -> str:
1021
+ """Return a user-friendly string representation."""
1022
+ ip_info = f", ip={self.ip}" if self.ip else ""
1023
+ return f"AnsibleHost(hostname='{self.hostname}'{ip_info})"
1024
+
1025
+ def __repr__(self) -> str:
1026
+ """Return a detailed string representation for debugging."""
1027
+ inv_str = self.inventory if isinstance(self.inventory, str) else f"[{', '.join(self.inventory)}]"
1028
+ ip_info = f", ip={self.ip}" if self.ip else ""
1029
+ v6_info = f", v6ip={self.v6ip}" if self.v6ip else ""
1030
+ return f"AnsibleHost(inventory={inv_str}, hostname='{self.hostname}'{ip_info}{v6_info})"
1031
+
1032
+
1033
+ class AnsibleLocalhost(AnsibleHostsBase):
1034
+ """Subclass for working with localhost."""
1035
+
1036
+ def __init__(
1037
+ self,
1038
+ inventory: str | list[str] | None = None,
1039
+ hostvars: dict[str, Any] | None = None,
1040
+ options: dict[str, Any] | None = None
1041
+ ) -> None:
1042
+ hostvars = hostvars or {}
1043
+ options = options or {}
1044
+
1045
+ # Set default options for localhost
1046
+ localhost_options = {
1047
+ "connection": "local"
1048
+ }
1049
+ localhost_options.update(options)
1050
+
1051
+ # If no inventory provided, use implicit localhost
1052
+ if not inventory:
1053
+ inventory = "/dev/null" # Ansible accepts this for implicit localhost
1054
+
1055
+ super().__init__(inventory=inventory, pattern="localhost", hostvars=hostvars, options=localhost_options)
1056
+
1057
+ # Add singular attributes like AnsibleHost
1058
+ self.hostname = "localhost"
1059
+
1060
+ def get_host_var(self, var_name: str, default: Any = None) -> Any:
1061
+ """Get a specific variable directly defined for localhost.
1062
+
1063
+ Returns only variables from host_vars/, not group_vars or other sources.
1064
+
1065
+ Args:
1066
+ var_name: Variable name to retrieve
1067
+ default: Default value to return if variable is not found
1068
+
1069
+ Returns:
1070
+ Value of the specific variable, or default if not found
1071
+ """
1072
+ return super().get_host_var(self.hostname, var_name, default)
1073
+
1074
+ def get_visible_var(self, var_name: str, default: Any = None) -> Any:
1075
+ """Get a specific variable visible to localhost.
1076
+
1077
+ Includes host_vars, group_vars, inventory vars, extra_vars.
1078
+ Jinja2 templates are automatically rendered.
1079
+
1080
+ Args:
1081
+ var_name: Variable name to retrieve
1082
+ default: Default value to return if variable is not found
1083
+
1084
+ Returns:
1085
+ Value of the specific variable, or default if not found
1086
+ """
1087
+ return super().get_visible_var(self.hostname, var_name, default)
1088
+
1089
+ def update_extra_vars(self, extra_vars: dict[str, Any]) -> None:
1090
+ """Update extra variables for localhost.
1091
+
1092
+ Args:
1093
+ extra_vars: Dictionary of variables to add/update in extra_vars
1094
+ """
1095
+ self.vm.extra_vars.update(extra_vars)
1096
+
1097
+ @property
1098
+ def host_vars(self) -> dict[str, Any]:
1099
+ """Variables directly defined for localhost (convenience property).
1100
+
1101
+ Returns:
1102
+ Dictionary of variables directly defined for localhost
1103
+ """
1104
+ return super()._get_host_vars_dict(self.hostname)
1105
+
1106
+ @property
1107
+ def visible_vars(self) -> dict[str, Any]:
1108
+ """All variables visible to localhost (convenience property).
1109
+
1110
+ Returns:
1111
+ Dictionary of all variables visible to localhost (computed/resolved)
1112
+ """
1113
+ return super()._get_visible_vars_dict(self.hostname)
1114
+
1115
+ def __str__(self) -> str:
1116
+ """Return a user-friendly string representation."""
1117
+ return "AnsibleLocalhost(hostname='localhost')"
1118
+
1119
+ def __repr__(self) -> str:
1120
+ """Return a detailed string representation for debugging."""
1121
+ inv_str = self.inventory if isinstance(self.inventory, str) else f"[{', '.join(self.inventory)}]"
1122
+ return f"AnsibleLocalhost(inventory={inv_str}, connection='local')"
1123
+
1124
+
1125
+ __all__ = [
1126
+ "AnsibleHost",
1127
+ "AnsibleHosts",
1128
+ "AnsibleHostsBase",
1129
+ "AnsibleLocalhost",
1130
+ "AnsibleModuleFailed",
1131
+ "MultipleAnsibleHostsError",
1132
+ "NoAnsibleHostError",
1133
+ "NoTasksError",
1134
+ "UnsupportedAnsibleModule",
1135
+ ]