diff --git a/plugins/guests/debian/cap/change_host_name.rb b/plugins/guests/debian/cap/change_host_name.rb index 84e1a4e16..2107ea9e4 100644 --- a/plugins/guests/debian/cap/change_host_name.rb +++ b/plugins/guests/debian/cap/change_host_name.rb @@ -4,9 +4,28 @@ module VagrantPlugins class ChangeHostName def self.change_host_name(machine, name) machine.communicate.tap do |comm| - if !comm.test("hostname --fqdn | grep '^#{name}$' || hostname --short | grep '^#{name}$'") - comm.sudo("sed -r -i 's/^(127[.]0[.]1[.]1[[:space:]]+).*$/\\1#{name} #{name.split('.')[0]}/' /etc/hosts") + + # Get the current hostname + # if existing fqdn setup improperly, this returns just hostname + old = '' + comm.sudo "hostname -f" do |type, data| + if type == :stdout + old = data.chomp + end + end + + # this works even if they're not both fqdn + if old.split('.')[0] != name.split('.')[0] + comm.sudo("sed -i 's/.*$/#{name.split('.')[0]}/' /etc/hostname") + + # hosts should resemble: + # 127.0.1.1 host.fqdn.com host + # First to set fqdn + comm.sudo("sed -i 's@#{old}@#{name}@' /etc/hosts") + # Second to set hostname + comm.sudo("sed -i 's@#{old.split('.')[0]}@#{name.split('.')[0]}@' /etc/hosts") + comm.sudo("hostname -F /etc/hostname") comm.sudo("hostname --fqdn > /etc/mailname") comm.sudo("ifdown -a; ifup -a; ifup eth0") diff --git a/plugins/guests/ubuntu/cap/change_host_name.rb b/plugins/guests/ubuntu/cap/change_host_name.rb index b7ba03773..6363ab732 100644 --- a/plugins/guests/ubuntu/cap/change_host_name.rb +++ b/plugins/guests/ubuntu/cap/change_host_name.rb @@ -4,9 +4,28 @@ module VagrantPlugins class ChangeHostName def self.change_host_name(machine, name) machine.communicate.tap do |comm| - if !comm.test("sudo hostname | grep '^#{name}$'") - comm.sudo("sed -i 's/.*$/#{name}/' /etc/hostname") - comm.sudo("sed -i 's@^\\(127[.]0[.]1[.]1[[:space:]]\\+\\)@\\1#{name} #{name.split('.')[0]} @' /etc/hosts") + + # Get the current hostname + # if existing fqdn setup improperly, this returns just hostname + old = '' + comm.sudo "hostname -f" do |type, data| + if type == :stdout + old = data.chomp + end + end + + # this works even if they're not both fqdn + if old.split('.')[0] != name.split('.')[0] + + comm.sudo("sed -i 's/.*$/#{name.split('.')[0]}/' /etc/hostname") + + # hosts should resemble: + # 127.0.1.1 host.fqdn.com host + # First to set fqdn + comm.sudo("sed -i 's@#{old}@#{name}@' /etc/hosts") + # Second to set hostname + comm.sudo("sed -i 's@#{old.split('.')[0]}@#{name.split('.')[0]}@' /etc/hosts") + if comm.test("[ `lsb_release -c -s` = hardy ]") # hostname.sh returns 1, so I grep for the right name in /etc/hostname just to have a 0 exitcode comm.sudo("/etc/init.d/hostname.sh start; grep '#{name}' /etc/hostname")