From b45d66a03659f8e4780b6b55e51edcbd2f6f012d Mon Sep 17 00:00:00 2001
From: MKhatibzadeh <32599707+masihkhatibzadeh99@users.noreply.github.com>
Date: Fri, 7 Feb 2025 18:13:43 +0330
Subject: [PATCH] fix: Ensure fqdn is treated as string in get_hostname_fqdn
 (#5993)
 
Explicitly cast fqdn to a string before processing.
 
Reference:https://github.com/canonical/cloud-init/commit/b45d66a03659f8e4780b6b55e51edcbd2f6f012d
Conflict:(1)delete ", _" for util.get_hostname_fqdn() result in new test, refer to commit 74e4349
(2)not change .github-cla-signers
(3)change cloudinit/tests/test_util.py not tests/unittests/test_util.py
 
Fixes GH-5989
 
Co-authored-by: masih.khatibzdeh <masih.khatibzadeh@snapp.cab>
---
 cloudinit/util.py            |  2 +-
 cloudinit/tests/test_util.py | 16 ++++++++++++++++
 2 files changed, 17 insertions(+), 1 deletion(-)
 
diff --git a/cloudinit/util.py b/cloudinit/util.py
index e380848..70e0b76 100644
--- a/cloudinit/util.py
+++ b/cloudinit/util.py
@@ -1027,7 +1027,7 @@ def get_hostname_fqdn(cfg, cloud, metadata_only=False):
     """
     if "fqdn" in cfg:
         # user specified a fqdn.  Default hostname then is based off that
-        fqdn = cfg['fqdn']
+        fqdn = str(cfg["fqdn"])
         hostname = get_cfg_option_str(cfg, "hostname", fqdn.split('.')[0])
     else:
         if "hostname" in cfg and cfg['hostname'].find('.') > 0:
diff --git a/cloudinit/tests/test_util.py b/cloudinit/tests/test_util.py
index 5fb2508..a51de4d 100644
--- a/cloudinit/tests/test_util.py
+++ b/cloudinit/tests/test_util.py
@@ -448,6 +448,22 @@ class TestGetHostnameFqdn(CiTestCase):
             [{'fqdn': True, 'metadata_only': False},
              {'metadata_only': False}], mycloud.calls)
 
+    def test_get_hostname_fqdn_from_numeric_fqdn(self):
+        """When cfg fqdn is numeric, ensure it is treated as a string."""
+        hostname, fqdn = util.get_hostname_fqdn(
+            cfg={"fqdn": 12345}, cloud=None
+        )
+        self.assertEqual("12345", hostname)
+        self.assertEqual("12345", fqdn)
+
+    def test_get_hostname_fqdn_from_numeric_fqdn_with_domain(self):
+        """When cfg fqdn is numeric with a domain, ensure correct parsing."""
+        hostname, fqdn = util.get_hostname_fqdn(
+            cfg={"fqdn": "12345.example.com"}, cloud=None
+        )
+        self.assertEqual("12345", hostname)
+        self.assertEqual("12345.example.com", fqdn)
+
     def test_get_hostname_fqdn_from_passes_metadata_only_to_cloud(self):
         """Calls to cloud.get_hostname pass the metadata_only parameter."""
         mycloud = FakeCloud('cloudhost', 'cloudhost.mycloud.com')
-- 
2.33.0

