From 4399cb5a357c266aa0968b0daff35138c98301b7 Mon Sep 17 00:00:00 2001 From: Felix Fontein Date: Sat, 6 Dec 2025 22:25:30 +0100 Subject: [PATCH] Improve JSON parsing error handling. (#1221) (cherry picked from commit 6ab8cc0d82717225f6990e82a9d80ad6684a6bf3) --- changelogs/fragments/1221-cli-json-errors.yml | 3 +++ plugins/module_utils/common_cli.py | 26 ++++++++++++++----- 2 files changed, 23 insertions(+), 6 deletions(-) create mode 100644 changelogs/fragments/1221-cli-json-errors.yml diff --git a/changelogs/fragments/1221-cli-json-errors.yml b/changelogs/fragments/1221-cli-json-errors.yml new file mode 100644 index 00000000..9798ff49 --- /dev/null +++ b/changelogs/fragments/1221-cli-json-errors.yml @@ -0,0 +1,3 @@ +bugfixes: + - "CLI-based modules - when parsing JSON output fails, also provide standard error output. Also provide information on the command and its result in machine-readable way + (https://github.com/ansible-collections/community.docker/issues/1216, https://github.com/ansible-collections/community.docker/pull/1221)." diff --git a/plugins/module_utils/common_cli.py b/plugins/module_utils/common_cli.py index 4d1c032d..1965ad82 100644 --- a/plugins/module_utils/common_cli.py +++ b/plugins/module_utils/common_cli.py @@ -133,11 +133,18 @@ class AnsibleDockerClientBase(object): try: data = json.loads(stdout) except Exception as exc: - self.fail('Error while parsing JSON output of {cmd}: {exc}\nJSON output: {stdout}'.format( + self.fail( + 'Error while parsing JSON output of {cmd}: {exc}\nJSON output: {stdout}\n\nError output:\n{stderr}'.format( + cmd=self._compose_cmd_str(args), + exc=to_native(exc), + stdout=to_native(stdout), + stderr=to_native(stderr), + ), cmd=self._compose_cmd_str(args), - exc=to_native(exc), + rc=rc, stdout=to_native(stdout), - )) + stderr=to_native(stderr), + ) return rc, data, stderr # def call_cli_json_stream(self, *args, check_rc=False, data=None, cwd=None, environ_update=None, warn_on_stderr=False): @@ -153,11 +160,18 @@ class AnsibleDockerClientBase(object): if line.startswith(b'{'): result.append(json.loads(line)) except Exception as exc: - self.fail('Error while parsing JSON output of {cmd}: {exc}\nJSON output: {stdout}'.format( + self.fail( + 'Error while parsing JSON output of {cmd}: {exc}\nJSON output: {stdout}\n\nError output:\n{stderr}'.format( + cmd=self._compose_cmd_str(args), + exc=to_native(exc), + stdout=to_native(stdout), + stderr=to_native(stderr), + ), cmd=self._compose_cmd_str(args), - exc=to_native(exc), + rc=rc, stdout=to_native(stdout), - )) + stderr=to_native(stderr), + ) return rc, result, stderr @abc.abstractmethod