Issue#

After renaming a server with hostnamectl, every sudo command prints a warning and pauses for a few seconds before it runs:

sudo: unable to resolve host web-01: Name or service not known

The command still runs, but scripts and SSH sessions slow down, and some tools that look up the local hostname (mail, Java apps, clustering software) fail.

Cause#

sudo looks up the machine's own hostname so it can match Host entries in /etc/sudoers. hostnamectl set-hostname only updates /etc/hostname and the kernel hostname. It does not add the new name to /etc/hosts.

When the name isn't in /etc/hosts, the lookup falls through to DNS. If DNS doesn't know the name either, the lookup fails. You see the warning, and you also wait for the DNS timeout.

On cloud images there is a second trap: cloud-init can regenerate /etc/hosts on every boot, which undoes manual edits.

Solution#

  1. Check the current hostname and see whether it resolves:
hostname getent hosts "$(hostname)" || echo "not resolvable"
  1. Add the hostname to /etc/hosts. On Debian/Ubuntu the convention is to map it to 127.0.1.1. sudo still works here; it only shows the warning.
sudo sed -i '/^127\.0\.1\.1/d' /etc/hosts echo "127.0.1.1 $(hostname)" | sudo tee -a /etc/hosts

If the server has a static IP and an FQDN, use that instead:

192.168.10.21 web-01.example.com web-01
  1. On cloud VMs, check whether cloud-init manages /etc/hosts:
grep -rn manage_etc_hosts /etc/cloud/cloud.cfg /etc/cloud/cloud.cfg.d/

If manage_etc_hosts: true is set, put your change in the template so it survives a reboot:

sudo nano /etc/cloud/templates/hosts.debian.tmpl

You can also let cloud-init own the hostname entirely. Set manage_etc_hosts: false and keep your manual /etc/hosts instead.

  1. For future renames, update both files together:
NEW=web-02 sudo hostnamectl set-hostname "$NEW" sudo sed -i "s/^127\.0\.1\.1.*/127.0.1.1 $NEW/" /etc/hosts

Verify#

getent hosts "$(hostname)" sudo true && echo "sudo OK"

The getent output should show the hostname mapped to an address. sudo should return right away with no unable to resolve host warning. Reboot once on cloud VMs to confirm that cloud-init doesn't revert the change.

Tip: hostname -f should also return the FQDN without errors. If it fails, the order of names on the /etc/hosts line is wrong. The FQDN must come first, then the short name.