diff --git a/test/test_backends.py b/test/test_backends.py index 7c5809e3..1b7b45ba 100644 --- a/test/test_backends.py +++ b/test/test_backends.py @@ -476,6 +476,40 @@ def test_ansible_unknown_option(): runner.options_to_cli({"unknown": True}) +def test_ansible_run_module_uses_tree_callback(monkeypatch): + runner = AnsibleRunner() + monkeypatch.setenv("ANSIBLE_CALLBACKS_ENABLED", "profile_tasks") + + def run_expect(expected, cmd, *args): + assert expected == [0, 2, 8] + assert "--tree" not in cmd + assert cmd.startswith( + "ANSIBLE_CALLBACKS_ENABLED=%s " + "ANSIBLE_CALLBACK_TREE_DIR=%s ansible" + ) + assert args[0] == "profile_tasks,tree" + + tree_dir = args[1] + with open( + os.path.join(tree_dir, "host"), "w", encoding="ascii" + ) as result_file: + result_file.write('{"changed": false, "ping": "pong"}') + + class Result: + stdout = "" + + return Result() + + monkeypatch.setattr( + "testinfra.utils.ansible_runner.local.run_expect", run_expect + ) + + assert runner.run_module("host", "ping", None) == { + "changed": False, + "ping": "pong", + } + + def test_backend_importables(): # check that all declared backends are importable and the backend name # is set correctly diff --git a/testinfra/utils/ansible_runner.py b/testinfra/utils/ansible_runner.py index a70dec03..0d923ea8 100644 --- a/testinfra/utils/ansible_runner.py +++ b/testinfra/utils/ansible_runner.py @@ -371,7 +371,21 @@ def run_module( get_encoding: Callable[[], str] | None = None, **options: Any, ) -> Any: - cmd, args = "ansible --tree %s", [] + callbacks_enabled = os.environ.get("ANSIBLE_CALLBACKS_ENABLED") + if callbacks_enabled is None: + callbacks_enabled = self.ansible_config.get( + "defaults", "callbacks_enabled", fallback="" + ) + callbacks = [ + callback.strip() + for callback in callbacks_enabled.split(",") + if callback.strip() + ] + if "tree" not in callbacks and "ansible.builtin.tree" not in callbacks: + callbacks.append("tree") + + cmd = "ANSIBLE_CALLBACKS_ENABLED=%s ANSIBLE_CALLBACK_TREE_DIR=%s ansible" + args = [",".join(callbacks)] if self.inventory_file: cmd += " -i %s" args += [self.inventory_file] @@ -387,7 +401,7 @@ def run_module( cmd += " %s" args += [host] with tempfile.TemporaryDirectory() as d: - args.insert(0, d) + args.insert(1, d) out = local.run_expect([0, 2, 8], cmd, *args) files = os.listdir(d) if not files and "skipped" in out.stdout.lower():