From 7f7008fecc9e5d16340e9b0bff510b7cde2f2cfd Mon Sep 17 00:00:00 2001 From: Bikouo Aubin <79859644+abikouo@users.noreply.github.com> Date: Thu, 28 Jul 2022 16:24:35 +0200 Subject: [PATCH] k8s_log - fix module traceback when resource not found (#493) k8s_log - fix module traceback when resource not found Depends-on: #495 SUMMARY closes #479 ISSUE TYPE Bugfix Pull Request COMPONENT NAME k8s_log Reviewed-by: Mike Graves --- ...8s_log-fix-module-when-pod-does-exist.yaml | 3 +++ plugins/modules/k8s_log.py | 20 ++++++++++++++++--- .../targets/k8s_log/tasks/main.yml | 13 ++++++++++++ 3 files changed, 33 insertions(+), 3 deletions(-) create mode 100644 changelogs/fragments/493-k8s_log-fix-module-when-pod-does-exist.yaml diff --git a/changelogs/fragments/493-k8s_log-fix-module-when-pod-does-exist.yaml b/changelogs/fragments/493-k8s_log-fix-module-when-pod-does-exist.yaml new file mode 100644 index 00000000..cca11843 --- /dev/null +++ b/changelogs/fragments/493-k8s_log-fix-module-when-pod-does-exist.yaml @@ -0,0 +1,3 @@ +--- +bugfixes: + - k8s_log - Fix module traceback when no resource found (https://github.com/ansible-collections/kubernetes.core/issues/479). diff --git a/plugins/modules/k8s_log.py b/plugins/modules/k8s_log.py index fd0c8eea..41f4d49f 100644 --- a/plugins/modules/k8s_log.py +++ b/plugins/modules/k8s_log.py @@ -152,6 +152,12 @@ from ansible_collections.kubernetes.core.plugins.module_utils.k8s.service import K8sService, ) +try: + from kubernetes.client.exceptions import ApiException +except ImportError: + # ImportError are managed by the common module already. + pass + def argspec(): args = copy.deepcopy(AUTH_ARG_SPEC) @@ -217,9 +223,17 @@ def execute_module(svc, params): {"tailLines": params["tail_lines"]} ) - response = resource.log.get( - name=name, namespace=namespace, serialize=False, **kwargs - ) + try: + response = resource.log.get( + name=name, namespace=namespace, serialize=False, **kwargs + ) + except ApiException as exc: + if exc.reason == "Not Found": + raise CoreException("Pod {0}/{1} not found.".format(namespace, name)) + raise CoreException( + "Unable to retrieve log from Pod due to: {0}".format(exc.reason) + ) + log = response.data.decode("utf8") return {"changed": False, "log": log, "log_lines": log.split("\n")} diff --git a/tests/integration/targets/k8s_log/tasks/main.yml b/tests/integration/targets/k8s_log/tasks/main.yml index 336e6e1c..d4769e09 100644 --- a/tests/integration/targets/k8s_log/tasks/main.yml +++ b/tests/integration/targets/k8s_log/tasks/main.yml @@ -1,5 +1,18 @@ --- - block: + - name: Retrieve log from unexisting Pod + k8s_log: + namespace: "{{ test_namespace }}" + name: "this_pod_does_exist" + ignore_errors: true + register: fake_pod + + - name: Assert that task failed with proper message + assert: + that: + - fake_pod is failed + - 'fake_pod.msg == "Pod {{ test_namespace }}/this_pod_does_exist not found."' + - name: create hello-world deployment k8s: wait: yes