Why does my server's hostname keep changing?
Cloud-init runs on every boot and resets your hostname to the value provided by the server's metadata. This is expected behavior, but it means any hostname you set manually will be overwritten on the next reboot.
There are two ways to make your hostname persistent.
Option 1: Prevent cloud-init from changing the hostname
Add preserve_hostname: true to your cloud-init configuration. This tells cloud-init to leave the hostname alone after the first boot.
Step 1: Edit the cloud-init config file on your server:
sudo nano /etc/cloud/cloud.cfg
Step 2: Find the line preserve_hostname and set it to true (or add it if it's missing):
preserve_hostname: true
Step 3: Set your desired hostname:
sudo hostnamectl set-hostname your-desired-hostname
Step 4: Verify it survives a reboot:
sudo reboot # After reconnecting: hostname
Option 2: Set the hostname via cloud-init user data
If you want cloud-init to actively set a specific hostname on every boot, define it in your user data. This is useful if you are provisioning new servers and want the hostname baked into the configuration.
Add the following to your cloud-config user data:
#cloud-config hostname: your-desired-hostname fqdn: your-desired-hostname.example.com preserve_hostname: true
The hostname key sets the short hostname, fqdn sets the fully qualified domain name, and preserve_hostname: true ensures subsequent boots do not override your setting with metadata from the datasource.
Which option should I use?
| Situation | Recommended option |
|---|---|
| Existing server, changing hostname once | Option 1 |
| Provisioning new servers via user data | Option 2 |
Still seeing the hostname reset?
Check whether your datasource is overriding the hostname at the network stage. You can inspect what cloud-init did on the last boot with:
sudo cat /var/log/cloud-init.log | grep -i hostname
If you see entries showing the hostname being set from metadata after your change, confirm that preserve_hostname: true is present and correctly indented in /etc/cloud/cloud.cfg.
Was this article helpful?
That’s Great!
Thank you for your feedback
Sorry! We couldn't be helpful
Thank you for your feedback
Feedback sent
We appreciate your effort and will try to fix the article