Description: don't blank password when unlock writes to stderr
 Unlocking can succeed while sssd emits unrelated stderr. Check the
 shadow password after unlocking before falling back to clearing an empty
 locked password, preserving existing password hashes.
Author: Nicholas Lindsey <nicholas.lindsey@canonical.com>
Bug: https://bugs.launchpad.net/ubuntu/+source/cloud-init/+bug/2153951
Last-Update: 2026-11-10
Applied-Upstream: https://github.com/canonical/cloud-init/commit/29d50e12
--- a/cloudinit/distros/__init__.py
+++ b/cloudinit/distros/__init__.py
@@ -1062,9 +1062,11 @@ class Distro(persistence.CloudInitPickle
             util.logexc(LOG, "Failed to enable password for user %s", name)
             raise e
         if err:
-            # if "passwd" or "usermod" are unable to unlock an account with
-            # an empty password then they display a message on stdout. In
-            # that case then instead set a blank password.
+            LOG.debug(
+                "Unlocking password for %s wrote to stderr: %s", name, err
+            )
+        if err and self._shadow_file_has_empty_user_password(name):
+            # Unlocking an empty locked password can require clearing it.
             passwd_set_tools = (
                 ["passwd", "-d", name],
                 ["usermod", "--password", "''", name],
--- a/tests/unittests/distros/test_init.py
+++ b/tests/unittests/distros/test_init.py
@@ -549,3 +549,46 @@ class TestInstall:
         assert "Failed to install the following packages" in message
         for pkg in total_failed:
             assert pkg in message
+
+
+@pytest.mark.parametrize("tool", ["passwd", "usermod"])
+@pytest.mark.parametrize(
+    "password,stderr,blank",
+    [
+        ("$6$hash", "sss_cache warning", False),
+        ("!", "unlock failed", True),
+        ("", "unlock failed", True),
+        ("!", "", False),
+    ],
+)
+def test_unlock_passwd_checks_shadow(
+    mocker, tmp_path, tool, password, stderr, blank
+):
+    distro = get_distro("ubuntu")
+    shadow = tmp_path / "shadow"
+    shadow.write_text(f"alice:{password}:\n")
+    distro.shadow_fn = str(shadow)
+    mocker.patch("cloudinit.distros.util.system_is_snappy", return_value=False)
+    mocker.patch(
+        "cloudinit.distros.subp.which", side_effect=lambda name: name == tool
+    )
+    subp = mocker.patch(
+        "cloudinit.distros.subp.subp", return_value=("", stderr)
+    )
+
+    distro.unlock_passwd("alice")
+
+    unlock = (
+        ["passwd", "-u", "alice"]
+        if tool == "passwd"
+        else ["usermod", "--unlock", "alice"]
+    )
+    assert subp.call_args_list[0] == mock.call(unlock, rcs=[0, 3])
+    if blank:
+        command = (
+            ["passwd", "-d", "alice"]
+            if tool == "passwd"
+            else ["usermod", "--password", "''", "alice"]
+        )
+        assert subp.call_args_list[1] == mock.call(command)
+    assert subp.call_count == 1 + int(blank)
