fix(k8s): emit warnings via AnsibleModule.warn instead of exit_json (#1267)

SUMMARY
runner.py put warnings into the result dict that run_module() and k8s_service unpack into exit_json()/fail_json(). Passing warnings that way is deprecated since ansible-core 2.19 and goes away in 2.23, so every k8s or k8s_service run that produced a warning also emitted a deprecation warning. All five sites now use AnsibleModule.warn.
This also fixes a quieter bug in the same code. For a multi-document manifest run_module() returns {"changed": ..., "result": {"results": results}}, so warnings ended up nested at result.results[*].warnings, where ansible-core never looked. They were silently dropped whenever a task handled more than one resource, and are now shown.
#1033 fixed this class of bug in k8s_drain, k8s_rollback and k8s_scale for #1031, but never touched runner.py.
Fixes #1264
ISSUE TYPE

Bugfix Pull Request

COMPONENT NAME
k8s
k8s_service
ADDITIONAL INFORMATION
Verified on kind (Kubernetes v1.37.0) with ansible-core 2.21.4
AI Assistance Disclosure
Generated: unit test is AI-generated,
Human Verified: test on the kind cluster performed by a human

Reviewed-by: Don Naro <dnaro@redhat.com>
Reviewed-by: Bikouo Aubin
This commit is contained in:
Yuriy Novostavskiy
2026-11-16 17:23:04 +00:00
committed by GitHub
parent 536eded7d0
commit 11b861f77e
3 changed files with 71 additions and 43 deletions
@@ -0,0 +1,4 @@
---
bugfixes:
- k8s, k8s_service - emit warnings through ``AnsibleModule.warn`` instead of putting them in the result dict that is unpacked into ``exit_json``/``fail_json``. Passing ``warnings`` that way is deprecated since ansible-core 2.19 and will be removed in 2.23, so every run that produced a warning (for example the "No meaningful diff was generated" hint, warnings returned by the Kubernetes API, or ``validate`` findings) also emitted a deprecation warning (https://github.com/ansible-collections/kubernetes.core/pull/1267).
- k8s - warnings raised while processing a multi-document manifest are now shown to the user. They were previously nested under ``result.results[*].warnings``, where ansible-core never picked them up, so they were silently dropped whenever more than one resource was processed (https://github.com/ansible-collections/kubernetes.core/pull/1267).
+6 -10
View File
@@ -92,10 +92,10 @@ def run_module(module) -> None:
for definition in definitions: for definition in definitions:
result = {"changed": False, "result": {}} result = {"changed": False, "result": {}}
warnings = []
if module.params.get("validate") is not None: if module.params.get("validate") is not None:
warnings = validate(client, module, definition) for warning in validate(client, module, definition):
module.warn(warning)
try: try:
result = perform_action(svc, definition, module.params) result = perform_action(svc, definition, module.params)
@@ -109,16 +109,12 @@ def run_module(module) -> None:
except AttributeError: except AttributeError:
pass pass
error["msg"] = to_native(e) error["msg"] = to_native(e)
if warnings:
error.setdefault("warnings", []).extend(warnings)
if module.params.get("continue_on_error"): if module.params.get("continue_on_error"):
result["error"] = error result["error"] = error
else: else:
module.fail_json(**error) module.fail_json(**error)
if warnings:
result.setdefault("warnings", []).extend(warnings)
changed |= result["changed"] changed |= result["changed"]
results.append(result) results.append(result)
@@ -177,7 +173,7 @@ def perform_action(svc, definition: Dict, params: Dict) -> Dict:
result["method"] = "apply" result["method"] = "apply"
elif not existing: elif not existing:
if state == "patched": if state == "patched":
result.setdefault("warnings", []).append( svc.module.warn(
"resource 'kind={kind},name={name}' was not found but will not be " "resource 'kind={kind},name={name}' was not found but will not be "
"created as 'state' parameter has been set to '{state}'".format( "created as 'state' parameter has been set to '{state}'".format(
kind=kind, name=definition["metadata"].get("name"), state=state kind=kind, name=definition["metadata"].get("name"), state=state
@@ -194,8 +190,8 @@ def perform_action(svc, definition: Dict, params: Dict) -> Dict:
instance, warnings = svc.update(resource, definition, existing) instance, warnings = svc.update(resource, definition, existing)
result["method"] = "update" result["method"] = "update"
if warnings: for warning in warnings:
result["warnings"] = warnings svc.module.warn(warning)
# If needed, wait and/or create diff # If needed, wait and/or create diff
success = True success = True
@@ -217,7 +213,7 @@ def perform_action(svc, definition: Dict, params: Dict) -> Dict:
existing = {} existing = {}
match, diffs = diff_objects(existing, instance, hidden_fields) match, diffs = diff_objects(existing, instance, hidden_fields)
if match and diffs: if match and diffs:
result.setdefault("warnings", []).append( svc.module.warn(
"No meaningful diff was generated, but the API may not be idempotent " "No meaningful diff was generated, but the API may not be idempotent "
"(only metadata.generation or metadata.resourceVersion were changed)" "(only metadata.generation or metadata.resourceVersion were changed)"
) )
+61 -33
View File
@@ -29,9 +29,21 @@ definition = {
modified_def = deepcopy(definition) modified_def = deepcopy(definition)
modified_def["metadata"]["labels"]["environment"] = "testing" modified_def["metadata"]["labels"]["environment"] = "testing"
# Differs from the above only in metadata.resourceVersion, which diff_objects()
# treats as a match while still producing a diff.
versioned_def = deepcopy(definition)
versioned_def["metadata"]["resourceVersion"] = "1"
rereconciled_def = deepcopy(definition)
rereconciled_def["metadata"]["resourceVersion"] = "2"
NO_MEANINGFUL_DIFF = (
"No meaningful diff was generated, but the API may not be idempotent "
"(only metadata.generation or metadata.resourceVersion were changed)"
)
@pytest.mark.parametrize( @pytest.mark.parametrize(
"action, params, existing, instance_warnings, expected", "action, params, existing, instance_warnings, expected, expected_warnings",
[ [
( (
"delete", "delete",
@@ -39,6 +51,7 @@ modified_def["metadata"]["labels"]["environment"] = "testing"
{}, {},
{}, {},
{"changed": False, "method": "delete", "result": {}}, {"changed": False, "method": "delete", "result": {}},
[],
), ),
( (
"delete", "delete",
@@ -46,6 +59,7 @@ modified_def["metadata"]["labels"]["environment"] = "testing"
definition, definition,
{"kind": "Status"}, {"kind": "Status"},
{"changed": True, "method": "delete", "result": {"kind": "Status"}}, {"changed": True, "method": "delete", "result": {"kind": "Status"}},
[],
), ),
( (
"apply", "apply",
@@ -53,31 +67,25 @@ modified_def["metadata"]["labels"]["environment"] = "testing"
{}, {},
(definition, []), (definition, []),
{"changed": True, "method": "apply", "result": definition}, {"changed": True, "method": "apply", "result": definition},
[],
), ),
( (
"apply", "apply",
{"apply": "yes"}, {"apply": "yes"},
{}, {},
(definition, ["test warning"]), (definition, ["test warning"]),
{ {"changed": True, "method": "apply", "result": definition},
"changed": True, ["test warning"],
"method": "apply",
"result": definition,
"warnings": ["test warning"],
},
), ),
( (
"create", "create",
{"state": "patched"}, {"state": "patched"},
{}, {},
({}, []), ({}, []),
{ {"changed": False, "result": {}},
"changed": False, [
"result": {}, "resource 'kind=Pod,name=foo' was not found but will not be created as 'state' parameter has been set to 'patched'"
"warnings": [ ],
"resource 'kind=Pod,name=foo' was not found but will not be created as 'state' parameter has been set to 'patched'"
],
},
), ),
( (
"create", "create",
@@ -85,18 +93,15 @@ modified_def["metadata"]["labels"]["environment"] = "testing"
{}, {},
(definition, []), (definition, []),
{"changed": True, "method": "create", "result": definition}, {"changed": True, "method": "create", "result": definition},
[],
), ),
( (
"create", "create",
{}, {},
{}, {},
(definition, ["test warning"]), (definition, ["test warning"]),
{ {"changed": True, "method": "create", "result": definition},
"changed": True, ["test warning"],
"method": "create",
"result": definition,
"warnings": ["test warning"],
},
), ),
( (
"replace", "replace",
@@ -104,6 +109,7 @@ modified_def["metadata"]["labels"]["environment"] = "testing"
definition, definition,
(definition, []), (definition, []),
{"changed": False, "method": "replace", "result": definition}, {"changed": False, "method": "replace", "result": definition},
[],
), ),
( (
"replace", "replace",
@@ -111,18 +117,15 @@ modified_def["metadata"]["labels"]["environment"] = "testing"
definition, definition,
(modified_def, []), (modified_def, []),
{"changed": True, "method": "replace", "result": modified_def}, {"changed": True, "method": "replace", "result": modified_def},
[],
), ),
( (
"replace", "replace",
{"force": "yes"}, {"force": "yes"},
definition, definition,
(modified_def, ["test warning"]), (modified_def, ["test warning"]),
{ {"changed": True, "method": "replace", "result": modified_def},
"changed": True, ["test warning"],
"method": "replace",
"result": modified_def,
"warnings": ["test warning"],
},
), ),
( (
"update", "update",
@@ -130,6 +133,7 @@ modified_def["metadata"]["labels"]["environment"] = "testing"
definition, definition,
(definition, []), (definition, []),
{"changed": False, "method": "update", "result": definition}, {"changed": False, "method": "update", "result": definition},
[],
), ),
( (
"update", "update",
@@ -137,18 +141,31 @@ modified_def["metadata"]["labels"]["environment"] = "testing"
definition, definition,
(modified_def, []), (modified_def, []),
{"changed": True, "method": "update", "result": modified_def}, {"changed": True, "method": "update", "result": modified_def},
[],
), ),
( (
"update", "update",
{}, {},
definition, definition,
(modified_def, ["test warning"]), (modified_def, ["test warning"]),
{ {"changed": True, "method": "update", "result": modified_def},
"changed": True, ["test warning"],
"method": "update", ),
"result": modified_def, (
"warnings": ["test warning"], "update",
}, {},
versioned_def,
(rereconciled_def, []),
{"changed": False, "method": "update", "result": rereconciled_def},
[NO_MEANINGFUL_DIFF],
),
(
"update",
{},
versioned_def,
(rereconciled_def, ["test warning"]),
{"changed": False, "method": "update", "result": rereconciled_def},
["test warning", NO_MEANINGFUL_DIFF],
), ),
( (
"create", "create",
@@ -159,6 +176,7 @@ modified_def["metadata"]["labels"]["environment"] = "testing"
"changed": False, "changed": False,
"msg": "resource 'kind=Pod,name=foo,namespace=foo' filtered by label_selectors.", "msg": "resource 'kind=Pod,name=foo,namespace=foo' filtered by label_selectors.",
}, },
[],
), ),
( (
"create", "create",
@@ -166,10 +184,13 @@ modified_def["metadata"]["labels"]["environment"] = "testing"
{}, {},
(definition, []), (definition, []),
{"changed": True, "method": "create", "result": definition}, {"changed": True, "method": "create", "result": definition},
[],
), ),
], ],
) )
def test_perform_action(action, params, existing, instance_warnings, expected): def test_perform_action(
action, params, existing, instance_warnings, expected, expected_warnings
):
svc = Mock() svc = Mock()
svc.find_resource.return_value = Mock( svc.find_resource.return_value = Mock(
kind=definition["kind"], group_version=definition["apiVersion"] kind=definition["kind"], group_version=definition["apiVersion"]
@@ -180,3 +201,10 @@ def test_perform_action(action, params, existing, instance_warnings, expected):
result = perform_action(svc, definition, params) result = perform_action(svc, definition, params)
assert expected.items() <= result.items() assert expected.items() <= result.items()
# Warnings must be emitted through AnsibleModule.warn, never smuggled into the
# result dict: run_module()/k8s_service unpack that dict into exit_json(), and
# passing `warnings` to exit_json() is deprecated since ansible-core 2.19
# (https://github.com/ansible-collections/kubernetes.core/issues/1264).
assert "warnings" not in result
assert [c.args[0] for c in svc.module.warn.call_args_list] == expected_warnings