Updating a Raspberry Pi hostname
I set up a Raspberry Pi running Ubuntu Server using the Raspberry Pi Imager app, which lets you preconfigure the hostname, user account, and SSH keys before you even boot the thing. Later on I wanted to rename it, so I did it the normal way with hostnamectl, rebooted to make sure it had taken, and found the old hostname was back.
A bit of digging turned up why: Raspberry Pi Imager does its configuration through cloud-init, and cloud-init reapplies its own settings, including the hostname, on every boot. Editing /etc/hostname directly, or running hostnamectl, doesn’t touch the configuration cloud-init is reading from, so the change never survives a reboot. Raspberry Pi Imager writes its configuration into /boot/firmware/user-data, and that’s the file cloud-init reads on boot, so it’s the one to check first:
cat /boot/firmware/user-data
If it has a hostname line, that’s the value winning out over anything set manually. Open the file and change it to the hostname you actually want, similar to hostname: greenhouse-pi:
sudo nano /boot/firmware/user-data
cloud-init caches state from its first run and won’t necessarily pick up the change on its own, so clear that out too:
sudo cloud-init clean --logs
Then reboot:
sudo reboot
On the way back up, cloud-init reads the updated user-data fresh and applies the new hostname properly, and this time it sticks.