From ec8942dd90601f9723dedd5941672bc14c033592 Mon Sep 17 00:00:00 2001 From: "W. H. Wang" Date: Fri, 7 Aug 2026 17:14:22 +0800 Subject: [PATCH] Handle empty template output gracefully (#1044) * Handle empty template output gracefully * Add changelog fragment for empty template output fix * refactor: reduce cognitive complexity of ActionModule.run Extract compound boolean condition to a variable to reduce the cognitive complexity from 16 to the allowed maximum of 15. Co-Authored-By: Claude Opus 4.6 * refactor: extract duplicated error handling into _fail_with_error Replace two identical error-handling blocks in ActionModule.run() with a shared _fail_with_error static method to address SonarQube code duplication finding. Co-Authored-By: Claude Opus 4.6 * refactor: reduce code duplication in action plugin and tests Revert _fail_with_error extraction that increased duplication on new code. Consolidate duplicate integration test tasks for conditional template into a single looped task. Co-Authored-By: Claude Opus 4.6 --------- Co-authored-by: aubin bikouo Co-authored-by: Claude Opus 4.6 --- .../20250108-fix-empty-template-output.yaml | 2 + plugins/action/k8s_info.py | 13 ++++- .../targets/k8s_template/tasks/main.yml | 48 +++++++++++++++++++ .../templates/conditional_empty.j2 | 12 +++++ 4 files changed, 73 insertions(+), 2 deletions(-) create mode 100644 changelogs/fragments/20250108-fix-empty-template-output.yaml create mode 100644 tests/integration/targets/k8s_template/templates/conditional_empty.j2 diff --git a/changelogs/fragments/20250108-fix-empty-template-output.yaml b/changelogs/fragments/20250108-fix-empty-template-output.yaml new file mode 100644 index 00000000..5582ad47 --- /dev/null +++ b/changelogs/fragments/20250108-fix-empty-template-output.yaml @@ -0,0 +1,2 @@ +bugfixes: +- k8s_info - Handle empty template output gracefully by returning ``changed=false`` instead of failing when Jinja2 template renders to an empty string (https://github.com/ansible-collections/kubernetes.core/issues/1042). diff --git a/plugins/action/k8s_info.py b/plugins/action/k8s_info.py index 390e3264..f47b9c73 100644 --- a/plugins/action/k8s_info.py +++ b/plugins/action/k8s_info.py @@ -35,7 +35,11 @@ def _from_yaml_to_definition(buffer): import yaml except ImportError: raise AnsibleError("Failed to import the required Python library (PyYAML).") - return list(yaml.safe_load_all(buffer)) + + # Handle empty template output + if buffer is None: + return [] + return [doc for doc in yaml.safe_load_all(buffer) if doc is not None] ENV_KUBECONFIG_PATH_SEPARATOR = ";" if platform.system() == "Windows" else ":" @@ -380,10 +384,15 @@ class ActionModule(ActionBase): template = self._task.args.get("template", None) if template: self.load_template(template, new_module_args, task_vars) + # If template rendered to empty definition, return early with no changes + if not new_module_args.get("definition"): + result["changed"] = False + return self._ensure_invocation(result) local_path = self._task.args.get("local_path") state = self._task.args.get("state", None) - if local_path and state == "to_pod" and not remote_transport: + is_local_pod_upload = local_path and state == "to_pod" and not remote_transport + if is_local_pod_upload: new_module_args["local_path"] = self.get_file_realpath(local_path) # Execute the k8s_* module. diff --git a/tests/integration/targets/k8s_template/tasks/main.yml b/tests/integration/targets/k8s_template/tasks/main.yml index 33eb4591..d23f1d1d 100644 --- a/tests/integration/targets/k8s_template/tasks/main.yml +++ b/tests/integration/targets/k8s_template/tasks/main.yml @@ -238,7 +238,55 @@ - resource.result.results | selectattr('changed') | list | length == 1 - resource.result.results | selectattr('error', 'defined') | list | length == 1 + - name: Apply template where all items are disabled (empty output) + kubernetes.core.k8s: + state: present + template: + path: "conditional_empty.j2" + vars: + items: + - name: test1 + enabled: false + - name: test2 + enabled: false + k8s_pod_namespace: "{{ template_namespace }}" + register: r + + - name: Check that empty template succeeds with no changes + assert: + that: + - r is successful + - r is not changed + + - name: Apply template where some items are enabled + kubernetes.core.k8s: + state: present + template: + path: "conditional_empty.j2" + vars: + items: + - name: conditional-configmap-1 + enabled: true + - name: conditional-configmap-2 + enabled: false + k8s_pod_namespace: "{{ template_namespace }}" + register: r + + - name: Check that partial template creates resources + assert: + that: + - r is successful + - r is changed + always: + - name: Cleanup conditional configmap + kubernetes.core.k8s: + state: absent + kind: ConfigMap + name: conditional-configmap-1 + namespace: "{{ template_namespace }}" + ignore_errors: true + - name: Remove namespace (Cleanup) kubernetes.core.k8s: kind: Namespace diff --git a/tests/integration/targets/k8s_template/templates/conditional_empty.j2 b/tests/integration/targets/k8s_template/templates/conditional_empty.j2 new file mode 100644 index 00000000..e12bcdc8 --- /dev/null +++ b/tests/integration/targets/k8s_template/templates/conditional_empty.j2 @@ -0,0 +1,12 @@ +{% for item in items %} +{% if item.enabled %} +--- +apiVersion: v1 +kind: ConfigMap +metadata: + name: "{{ item.name }}" + namespace: "{{ k8s_pod_namespace }}" +data: + key: value +{% endif %} +{% endfor %}