Ubuntu – “Unable to resolve hostname” – how to cleanly change hostname without rebooting

hostnamelinuxUbuntu

At work, I work on a small website using Ubuntu servers hosted on Amazon EC2 instances. We have two webservers, and at any given time one of them is 'live' and one is 'testing', but when we've got our new features or bugfixes working on the 'testing' server, we run a script that uses the AWS API to swap the IP addresses assigned to the two boxes so that the domains being served by the two servers are swapped.

Consequently, at any given moment, one of these servers can be either our 'live' server or our 'testing' server, but these are not permanent states.

To avoid confusion when SSHing into either of these servers, especially if some silly person (like me) leaves an SSH session open for a long time and gets confused about which server they're on, I want to modify the hostnames of the two servers so that the prompt and title in the terminal window will read ubuntu@ourwebsiteLIVE or ubuntu@ourwebsiteTESTING depending upon whether the server is currently live or testing.

I know I can do this by running hostname ourwebsiteLIVE etc. in our IP-swapping script, and have already implemented this. It works, but now every time I sudo anything on either of our servers it prints e.g.

sudo: unable to resolve host ourwebsiteLIVE

which doesn't seem to break anything, but is fairly irritating. I figure it also might end up breaking stuff in future if I try to chain commands that pipe output to each other, so I guess it's technically not just an aesthetics issue.

All the solutions I've seen to the 'unable to resolve hostname' message involve modifying /etc/hosts or some similar file and then rebooting the server. I can see that this would be fine for many use cases, but is far from ideal for us since we're modifying the hostname routinely and programmatically; we don't want to have to wait for a reboot every time we run our swap script.

Is there a way I can make the error message go away without having to reboot?

Best Answer

I would suggest using nss-myhostname. It is a nss plugin which just always resolves your current hostname, so there is no need to modify /etc/hosts.

As the issue you are describing is just a resolver issue you can fix it by having a proper DNS setup, i.e. ourwebsiteLIVE.$DOMAIN just resolves to the ip of the machine.

Related Question