{"library":"ansible-core","code":"import json\nimport shutil\nimport os\n\nimport ansible.constants as C\nfrom ansible.executor.task_queue_manager import TaskQueueManager\nfrom ansible.inventory.manager import InventoryManager\nfrom ansible.parsing.dataloader import DataLoader\nfrom ansible.playbook.play import Play\nfrom ansible.plugins.callback import CallbackBase\nfrom ansible.vars.manager import VariableManager\nfrom ansible import context\n\n# NOTE: The Ansible Python API is for internal use and not officially supported for external applications.\n# For robust programmatic execution of playbooks and modules, consider using 'ansible-runner'.\n\n# --- Minimal example to run a simple ad-hoc command --- \n\n# Configure Ansible context (optional, but good practice)\ncontext.CLIARGS = ['ansible', 'all', '-m', 'ping', '-i', 'localhost,'] # Mimics command line args\n\nclass ResultsCollectorJSONCallback(CallbackBase):\n    def __init__(self):\n        self.host_ok = {}\n        self.host_failed = {}\n        self.host_unreachable = {}\n    \n    def v2_runner_on_ok(self, result, **kwargs):\n        self.host_ok[result._host.get_name()] = result._result\n\n    def v2_runner_on_failed(self, result, **kwargs):\n        self.host_failed[result._host.get_name()] = result._result\n\n    def v2_runner_on_unreachable(self, result, **kwargs):\n        self.host_unreachable[result._host.get_name()] = result._result\n\n# initialize needed objects\nloader = DataLoader()\ninv_data = 'localhost ansible_connection=local'\ninventory = InventoryManager(loader=loader, sources=[inv_data])\nvariable_manager = VariableManager(loader=loader, inventory=inventory)\n\n# instantiate our callback plugin\nresults_callback = ResultsCollectorJSONCallback()\n\n# create play with tasks\nplay_source = dict(\n    name=\"Ansible Ad-hoc Ping\",\n    hosts='all',\n    gather_facts='no',\n    tasks=[\n        dict(action=dict(module='ping'), register='ping_result')\n    ]\n)\nplay = Play().load(play_source, variable_manager=variable_manager, loader=loader)\n\n# run it\nt = TaskQueueManager(\n    inventory=inventory,\n    variable_manager=variable_manager,\n    loader=loader,\n    options=context.CLIARGS,\n    passwords={},\n    stdout_callback=results_callback,\n)\n\ntry:\n    status = t.run(play)\nfinally:\n    # cleanup after ourselves\n    if t is not None:\n        t.cleanup()\n    if loader: # DataLoader may delete tmpdir on exit, ensure it's removed if exists\n        if hasattr(loader, '_tempdir') and os.path.exists(loader._tempdir):\n            shutil.rmtree(loader._tempdir)\n\nprint(\"\\n--- Ad-hoc Ping Results ---\")\nprint(f\"OK: {json.dumps(results_callback.host_ok, indent=4)}\")\nprint(f\"Failed: {json.dumps(results_callback.host_failed, indent=4)}\")\nprint(f\"Unreachable: {json.dumps(results_callback.host_unreachable, indent=4)}\")\n","lang":"python","description":"This quickstart demonstrates how to programmatically execute a simple 'ping' ad-hoc command using ansible-core's internal Python API. It sets up an in-memory inventory, defines a simple play, and uses a custom callback to capture results. Note that the Ansible Python API is primarily for internal use, and `ansible-runner` is generally recommended for external programmatic integration.","tag":null,"tag_description":null,"last_tested":"2026-04-24","results":[{"runtime":"python:3.10-alpine","exit_code":1},{"runtime":"python:3.10-slim","exit_code":1},{"runtime":"python:3.11-alpine","exit_code":1},{"runtime":"python:3.11-slim","exit_code":1},{"runtime":"python:3.12-alpine","exit_code":1},{"runtime":"python:3.12-slim","exit_code":1},{"runtime":"python:3.13-alpine","exit_code":1},{"runtime":"python:3.13-slim","exit_code":1},{"runtime":"python:3.9-alpine","exit_code":1},{"runtime":"python:3.9-slim","exit_code":1}]}