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 <noreply@anthropic.com>

* 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 <noreply@anthropic.com>

* 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 <noreply@anthropic.com>

---------

Co-authored-by: aubin bikouo <abikouo@redhat.com>
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
W. H. Wang
2026-08-07 11:14:22 +02:00
committed by GitHub
co-authored by aubin bikouo Claude Opus 4.6
parent 08a761fc17
commit ec8942dd90
4 changed files with 73 additions and 2 deletions
@@ -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).
+11 -2
View File
@@ -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.
@@ -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
@@ -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 %}