Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

How can I have an Ubuntu server VM set /etc/hostname/ to the value fo the VM's assigned IP address automatically on startup?

I'm creating an Ubuntu server VM image to run Hadoop. When a client interacts with Hadoop it returns addresses of nodes in the cluster (even if in this instance they're all processes on the same machine) for the client to interact with. These addresses are determined by Java's hostname resolution, which I gather is not at all reliable. I've been advised the best way around this is to set /etc/hostname/ to the assigned IP address of the only network interface. Alternatively there may be an approach of setting an environment variable and then passing this to the JVM running each Hadoop process.

share|improve this question
    
How is the IP set? DHCP? Would using a fixed IP be an option? –  terdon Mar 22 '13 at 15:55
add comment

2 Answers 2

up vote 4 down vote accepted

I added

hostname `hostname -I`

to '/etc/rc.local` and that set the hostname correctly to the currently-assigned IP address.

share|improve this answer
    
Now I feel silly. +1 –  terdon Mar 25 '13 at 20:28
    
This works for JMeter as well –  BCqrstoO Jul 18 at 16:55
add comment

Using a fixed IP would be the simplest solution. If you can do that, just change /etc/hostname on the guest so that it looks like this (using the right IP of course):

192.168.1.10

If you can't/don't want to use that, you can set up a cronjob that reads the system's IP and updates /etc/hostname accordingly. This command will give you your IP:

ifconfig | grep Bcast | awk '{print $2}' | sed 's/addr://'

Now add a new crontab for root:

sudo crontab -e

This will bring up whicever editor you have defined. Add this line to the crontab file:

@reboot ifconfig | grep Bcast | awk '{print $2}' | sed 's/addr://' > /etc/hostname

This will run the command once each time the machine boots and save its output (the IP) to /etc/hostname. A possible problem is that the cron daemon is started before an IP is assigned. In that case, you could set it to be run every five minutes or so:

*/5 * * * * ifconfig | grep Bcast | awk '{print $2}' | sed 's/addr://' > /etc/hostname
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.