From 044edf013707526995e871403b6857519e5dd964 Mon Sep 17 00:00:00 2001 From: Rick Rackow Date: Thu, 3 Apr 2025 21:04:10 +0200 Subject: [PATCH] fix(cloud-init): truncate all hostnames on first `.` This ensures consistent behaviour and only if the hostname still exceeds the character limit, it gets truncated further --- .../2025-04-03-sanitize-hostname.md | 2 ++ coreos-cloudinit.go | 13 +++++++------ coreos-cloudinit_test.go | 19 +++++++++++++++++++ 3 files changed, 28 insertions(+), 6 deletions(-) create mode 100644 changelog/enhancement/2025-04-03-sanitize-hostname.md diff --git a/changelog/enhancement/2025-04-03-sanitize-hostname.md b/changelog/enhancement/2025-04-03-sanitize-hostname.md new file mode 100644 index 0000000..ab1254f --- /dev/null +++ b/changelog/enhancement/2025-04-03-sanitize-hostname.md @@ -0,0 +1,2 @@ +* Always truncate hostnames on the first occurrence of `.` +* Ensure hostnames never exceeds 63 characters, regardless of the metadata provider diff --git a/coreos-cloudinit.go b/coreos-cloudinit.go index 82e4230..9b30afd 100644 --- a/coreos-cloudinit.go +++ b/coreos-cloudinit.go @@ -286,13 +286,14 @@ func determineHostname(md datasource.Metadata, udata *initialize.UserData) strin hostname = udataHostname } } + // Always truncate hostnames to everything before the first `.` + hostname = strings.Split(hostname, ".")[0] + + // Truncate after 63 characters if the hostname exceeds that if len(hostname) > 63 { - log.Printf("Hostname too long. Truncating hostname %s to %s", hostname, strings.Split(hostname, ".")[0]) - hostname = strings.Split(hostname, ".")[0] - if len(hostname) > 63 { - log.Printf("Hostname still too long. Truncating hostname %s further to 63 bytes (%s)", hostname, hostname[:63]) - hostname = hostname[:63] - } + log.Printf("Hostname too long. Truncating hostname %s to 63 bytes (%s)", hostname, hostname[:63]) + hostname = hostname[:63] + } return hostname } diff --git a/coreos-cloudinit_test.go b/coreos-cloudinit_test.go index 515f2aa..93870fd 100644 --- a/coreos-cloudinit_test.go +++ b/coreos-cloudinit_test.go @@ -105,6 +105,25 @@ func TestDetermineHostname(t *testing.T) { uData: nil, expect: "regular-name", }, + { + metaData: datasource.Metadata{ + PublicIPv4: net.ParseIP("1.2.3.4"), + PublicIPv6: net.ParseIP("5.6.7.8"), + PrivateIPv4: net.ParseIP("1.2.3.4"), + PrivateIPv6: net.ParseIP("5.6.7.8"), + Hostname: "regular-name.domain", + SSHPublicKeys: map[string]string{"my": "key"}, + NetworkConfig: net.Interface{ + Index: 0, + MTU: 0, + Name: "some-interface", + HardwareAddr: nil, + Flags: 0, + }, + }, + uData: nil, + expect: "regular-name", + }, { metaData: datasource.Metadata{ PublicIPv4: net.ParseIP("1.2.3.4"),