enhance hostname configuration to prevent cloud-init overwrites

This commit is contained in:
buildplan 2025-11-25 21:34:09 +00:00
parent ca160b3a4a
commit e59a56581f

View File

@ -3170,6 +3170,8 @@ configure_system() {
fi
print_info "Configuring hostname..."
# System Hostname
if [[ $(hostnamectl --static) != "$SERVER_NAME" ]]; then
hostnamectl set-hostname "$SERVER_NAME"
hostnamectl set-hostname "$PRETTY_NAME" --pretty
@ -3179,10 +3181,9 @@ configure_system() {
fi
if [[ -d /etc/cloud/cloud.cfg.d ]]; then
print_info "Disabling cloud-init host management via override file..."
# Create the override file to override provider defaults
echo "manage_etc_hosts: false" > /etc/cloud/cloud.cfg.d/99-du-setup-hosts.cfg
echo "preserve_hostname: true" >> /etc/cloud/cloud.cfg.d/99-du-setup-hosts.cfg
log "Created /etc/cloud/cloud.cfg.d/99-du-setup-hosts.cfg to prevent cloud-init reverts."
log "Created /etc/cloud/cloud.cfg.d/99-du-setup-hosts.cfg"
elif [[ -f /etc/cloud/cloud.cfg ]]; then
if grep -q "manage_etc_hosts: true" /etc/cloud/cloud.cfg; then
print_info "Disabling cloud-init 'manage_etc_hosts' in main config..."
@ -3191,6 +3192,25 @@ configure_system() {
fi
fi
# Stop cloud-init from overwriting /etc/hosts
local TEMPLATE_FILE=""
if [[ -n "$ID" && -f "/etc/cloud/templates/hosts.${ID}.tmpl" ]]; then
TEMPLATE_FILE="/etc/cloud/templates/hosts.${ID}.tmpl"
elif [[ -f "/etc/cloud/templates/hosts.tmpl" ]]; then
TEMPLATE_FILE="/etc/cloud/templates/hosts.tmpl"
fi
if [[ -n "$TEMPLATE_FILE" ]]; then
print_info "Patching cloud-init hosts template ($TEMPLATE_FILE) to enforce persistence..."
cp "$TEMPLATE_FILE" "$BACKUP_DIR/$(basename "$TEMPLATE_FILE").backup"
sed -i "s/^127.0.1.1.*/127.0.1.1\t$SERVER_NAME/g" "$TEMPLATE_FILE"
log "Hardcoded hostname into $TEMPLATE_FILE"
else
if [[ -d /etc/cloud/templates ]]; then
print_warning "Could not locate a standard hosts template in /etc/cloud/templates."
log "Warning: Cloud-init template patching skipped (no matching template found)."
fi
fi
if grep -q "^127.0.1.1" /etc/hosts; then
if ! grep -qE "^127.0.1.1[[:space:]]+$SERVER_NAME" /etc/hosts; then
sed -i "s/^127.0.1.1.*/127.0.1.1\t$SERVER_NAME/" /etc/hosts