feat(helm): add cleanup_on_fail option (#1206) (#1210)

* feat(helm): add cleanup_on_fail option

atomic rolls back to the last successful revision but can leave behind
resources the failed upgrade created; helm accepts both flags together so
the rollback also drops those orphans.

Rejected with replace=true, since that deploys via helm install, which has
no --cleanup-on-fail. No version gate: the flag exists in helm 3.0.0, the
module's minimum, and was not renamed in v4.

* refactor(tests): share helm command-building test helpers

The new cleanup_on_fail tests copied setUp and _run_with_version verbatim
from the atomic tests, which SonarQube flagged as duplication on new code.
Extract both to module level so the two classes share them.

Scoped to the classes involved in that duplication; the other test classes
in this file keep their own fixtures.

* test(helm): align cleanup_on_fail assertions with review feedback

Adjust the Helm unit tests to assert the expected flags for
cleanup_on_fail on Helm v3 and v4, matching the behavior clarified
in review feedback.



---------


(cherry picked from commit d4ef10fc80)

Co-authored-by: Yuriy Novostavskiy <yuriy@novostavskiy.kyiv.ua>
Co-authored-by: abikouo <abikouo@users.noreply.github.com>
This commit is contained in:
patchback[bot]
2026-08-10 16:41:33 +02:00
committed by GitHub
co-authored by Yuriy Novostavskiy abikouo
parent fd65a4f09e
commit 477bb79305
4 changed files with 189 additions and 33 deletions
@@ -0,0 +1,3 @@
---
minor_changes:
- helm - add the ``cleanup_on_fail`` option, mapping to the ``--cleanup-on-fail`` flag, to allow deletion of new resources created during a failed upgrade. It complements ``atomic`` and can be combined with it, but cannot be used with ``replace``, since that deploys through ``helm install`` which does not accept the flag (https://github.com/ansible-collections/kubernetes.core/pull/1206).
+23
View File
@@ -157,6 +157,29 @@ Parameters
<div>Chart version to install. If this is not specified, the latest version is installed.</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>cleanup_on_fail</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">boolean</span>
</div>
<div style="font-style: italic; font-size: small; color: darkgreen">added in 6.6.0</div>
</td>
<td>
<ul style="margin: 0; padding: 0"><b>Choices:</b>
<li><div style="color: blue"><b>no</b>&nbsp;&larr;</div></li>
<li>yes</li>
</ul>
</td>
<td>
<div>Allow deletion of new resources created during a failed upgrade.</div>
<div>Maps to the <code>--cleanup-on-fail</code> flag, which is available since helm 3.0.0 and was not renamed in Helm v4.</div>
<div>Complements O(atomic) rather than replacing it, and the two can be combined so that a rollback also drops resources orphaned by the failed upgrade.</div>
<div>Helm only accepts this flag on <code>helm upgrade</code>, so it cannot be used together with O(replace), which deploys through <code>helm install</code>.</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
+28
View File
@@ -207,6 +207,18 @@ options:
O(atomic) option works the same way regardless of the installed Helm version.
type: bool
default: False
cleanup_on_fail:
description:
- Allow deletion of new resources created during a failed upgrade.
- Maps to the C(--cleanup-on-fail) flag, which is available since helm 3.0.0 and
was not renamed in Helm v4.
- Complements O(atomic) rather than replacing it, and the two can be combined so
that a rollback also drops resources orphaned by the failed upgrade.
- Helm only accepts this flag on C(helm upgrade), so it cannot be used together
with O(replace), which deploys through C(helm install).
type: bool
default: False
version_added: 6.6.0
server_side:
description:
- Control Helm v4 server-side apply when installing or upgrading a release.
@@ -607,6 +619,7 @@ def deploy(
values_files,
history_max,
atomic=False,
cleanup_on_fail=False,
create_namespace=False,
replace=False,
post_renderer=None,
@@ -667,6 +680,17 @@ def deploy(
else:
deploy_command += " --atomic"
if cleanup_on_fail:
# '--cleanup-on-fail' is only accepted by 'helm upgrade', so it cannot be
# combined with 'replace', which deploys through 'helm install'. The flag
# exists since helm 3.0.0 and kept its name in v4, so no version gate is
# needed on top of the module-wide helm >= 3.0.0 requirement.
if replace:
module.fail_json(
msg="cleanup_on_fail is only supported by 'helm upgrade' and cannot be used with replace=true"
)
deploy_command += " --cleanup-on-fail"
if timeout:
deploy_command += " --timeout " + timeout
@@ -962,6 +986,7 @@ def argument_spec():
wait_timeout=dict(type="str"),
timeout=dict(type="str"),
atomic=dict(type="bool", default=False),
cleanup_on_fail=dict(type="bool", default=False),
server_side=dict(type="str", choices=["auto", "true", "false"]),
force_conflicts=dict(type="bool", default=False),
create_namespace=dict(type="bool", default=False),
@@ -1027,6 +1052,7 @@ def main():
wait = module.params.get("wait")
wait_timeout = module.params.get("wait_timeout")
atomic = module.params.get("atomic")
cleanup_on_fail = module.params.get("cleanup_on_fail")
server_side = module.params.get("server_side")
force_conflicts = module.params.get("force_conflicts")
create_namespace = module.params.get("create_namespace")
@@ -1157,6 +1183,7 @@ def main():
False,
values_files=values_files,
atomic=atomic,
cleanup_on_fail=cleanup_on_fail,
server_side=server_side,
force_conflicts=force_conflicts,
create_namespace=create_namespace,
@@ -1243,6 +1270,7 @@ def main():
force,
values_files=values_files,
atomic=atomic,
cleanup_on_fail=cleanup_on_fail,
server_side=server_side,
force_conflicts=force_conflicts,
create_namespace=create_namespace,
+135 -33
View File
@@ -23,6 +23,48 @@ from ansible_collections.kubernetes.core.tests.unit.utils.ansible_module_mock im
set_module_args,
)
CHART_INFO = {
"apiVersion": "v2",
"appVersion": "default",
"description": "A chart used in molecule tests",
"name": "test-chart",
"type": "application",
"version": "0.1.0",
}
def patch_ansible_module(test_case):
"""Patch AnsibleModule's exit/fail/bin-path hooks for the duration of test_case."""
mock_module_helper = patch.multiple(
basic.AnsibleModule,
exit_json=exit_json,
fail_json=fail_json,
get_bin_path=get_bin_path,
)
mock_module_helper.start()
test_case.addCleanup(mock_module_helper.stop)
def deploy_command_for_version(args, helm_version):
"""Run helm.main() against a mocked helm of helm_version and return its command.
Only the fresh-install path is mocked, so the caller sees the command built by
deploy(). Failures raised by the module (AnsibleFailJson) propagate to the test.
"""
set_module_args(args)
helm.get_release_status = MagicMock(return_value=None)
helm.fetch_chart_info = MagicMock(return_value=CHART_INFO)
with patch.object(
helm.AnsibleHelmModule, "get_helm_version", return_value=helm_version
):
with patch.object(basic.AnsibleModule, "run_command") as mock_run_command:
mock_run_command.return_value = (0, "configuration updated", "")
try:
helm.main()
except AnsibleExitJson as exc:
return exc.args[0]["command"]
raise AssertionError("helm.main() did not exit successfully")
class TestDependencyUpdateWithoutChartRepoUrlOption(unittest.TestCase):
def setUp(self):
@@ -716,39 +758,10 @@ class TestAtomicFlagHelmVersion(unittest.TestCase):
"""Helm v4 renamed '--atomic' to '--rollback-on-failure' (issue #1143)."""
def setUp(self):
self.mock_module_helper = patch.multiple(
basic.AnsibleModule,
exit_json=exit_json,
fail_json=fail_json,
get_bin_path=get_bin_path,
)
self.mock_module_helper.start()
self.addCleanup(self.mock_module_helper.stop)
self.chart_info = {
"apiVersion": "v2",
"appVersion": "default",
"description": "A chart used in molecule tests",
"name": "test-chart",
"type": "application",
"version": "0.1.0",
}
def _run_with_version(self, args, helm_version):
set_module_args(args)
helm.get_release_status = MagicMock(return_value=None)
helm.fetch_chart_info = MagicMock(return_value=self.chart_info)
with patch.object(
helm.AnsibleHelmModule, "get_helm_version", return_value=helm_version
):
with patch.object(basic.AnsibleModule, "run_command") as mock_run_command:
mock_run_command.return_value = (0, "configuration updated", "")
with self.assertRaises(AnsibleExitJson) as result:
helm.main()
return result.exception.args[0]["command"]
patch_ansible_module(self)
def test_atomic_uses_atomic_flag_on_helm_v3(self):
command = self._run_with_version(
command = deploy_command_for_version(
{
"release_name": "test",
"release_namespace": "test",
@@ -761,7 +774,7 @@ class TestAtomicFlagHelmVersion(unittest.TestCase):
assert "--rollback-on-failure" not in command
def test_atomic_uses_rollback_on_failure_on_helm_v4(self):
command = self._run_with_version(
command = deploy_command_for_version(
{
"release_name": "test",
"release_namespace": "test",
@@ -775,7 +788,7 @@ class TestAtomicFlagHelmVersion(unittest.TestCase):
def test_atomic_with_replace_uses_rollback_on_failure_on_helm_v4(self):
# 'replace' uses 'helm install', where '--atomic' is removed in v4.
command = self._run_with_version(
command = deploy_command_for_version(
{
"release_name": "test",
"release_namespace": "test",
@@ -788,3 +801,92 @@ class TestAtomicFlagHelmVersion(unittest.TestCase):
assert " install " in command
assert "--rollback-on-failure" in command
assert "--atomic" not in command
class TestCleanupOnFail(unittest.TestCase):
"""'--cleanup-on-fail' is upgrade-only and unchanged in Helm v4 (issue #1198)."""
def setUp(self):
patch_ansible_module(self)
def test_cleanup_on_fail_not_set_by_default(self):
command = deploy_command_for_version(
{
"release_name": "test",
"release_namespace": "test",
"chart_ref": "chart1",
},
"3.17.0",
)
assert "--cleanup-on-fail" not in command
def test_cleanup_on_fail_on_helm_v3(self):
# '--cleanup-on-fail' exists since helm 3.0.0, the module-wide minimum.
command = deploy_command_for_version(
{
"release_name": "test",
"release_namespace": "test",
"chart_ref": "chart1",
"cleanup_on_fail": True,
},
"3.0.0",
)
assert " upgrade -i" in command
assert "--cleanup-on-fail" in command
def test_cleanup_on_fail_keeps_same_flag_on_helm_v4(self):
# Unlike '--atomic', the flag was not renamed in Helm v4.
command = deploy_command_for_version(
{
"release_name": "test",
"release_namespace": "test",
"chart_ref": "chart1",
"cleanup_on_fail": True,
},
"4.0.0",
)
assert "--cleanup-on-fail" in command
def test_cleanup_on_fail_combines_with_atomic_on_helm_v3(self):
command = deploy_command_for_version(
{
"release_name": "test",
"release_namespace": "test",
"chart_ref": "chart1",
"atomic": True,
"cleanup_on_fail": True,
},
"3.17.0",
)
assert "--atomic" in command
assert "--rollback-on-failure" not in command
assert "--cleanup-on-fail" in command
def test_cleanup_on_fail_combines_with_atomic_on_helm_v4(self):
command = deploy_command_for_version(
{
"release_name": "test",
"release_namespace": "test",
"chart_ref": "chart1",
"atomic": True,
"cleanup_on_fail": True,
},
"4.0.0",
)
assert "--rollback-on-failure" in command
assert "--atomic" not in command
assert "--cleanup-on-fail" in command
def test_cleanup_on_fail_with_replace_fails(self):
# 'replace' deploys via 'helm install', which has no '--cleanup-on-fail'.
with self.assertRaises(AnsibleFailJson):
deploy_command_for_version(
{
"release_name": "test",
"release_namespace": "test",
"chart_ref": "chart1",
"cleanup_on_fail": True,
"replace": True,
},
"3.17.0",
)