diff --git a/plugins/guests/ubuntu/cap/change_host_name.rb b/plugins/guests/ubuntu/cap/change_host_name.rb index df68a010a..bbcada3e7 100644 --- a/plugins/guests/ubuntu/cap/change_host_name.rb +++ b/plugins/guests/ubuntu/cap/change_host_name.rb @@ -1,50 +1,51 @@ module VagrantPlugins module GuestUbuntu module Cap - class ChangeHostName < VagrantPlugins::GuestDebian::Cap::ChangeHostName + class ChangeHostName def self.change_host_name(machine, name) - super - end + comm = machine.communicate - def update_etc_hostname - return super unless systemd? - sudo("hostnamectl set-hostname '#{short_hostname}'") - end + if !comm.test("hostname -f | grep -w '#{name}'") + basename = name.split(".", 2)[0] + comm.sudo <<-EOH.gsub(/^ {14}/, '') + # Set the hostname + echo '#{name}' > /etc/hostname + hostname -F /etc/hostname - def refresh_hostname_service - if hardy? - # hostname.sh returns 1, so use `true` to get a 0 exitcode - sudo("/etc/init.d/hostname.sh start; true") - elsif systemd? - # Service runs via hostnamectl - else - sudo("service hostname start") + if command -v hostnamectl; then + hostnamectl set-hostname '#{name}' + fi + + # Remove comments and blank lines from /etc/hosts + sed -i'' -e 's/#.*$//' -e '/^$/d' /etc/hosts + + # Prepend ourselves to /etc/hosts + grep -w '#{name}' /etc/hosts || { + sed -i'' '1i 127.0.0.1\\t#{name}\\t#{basename}' /etc/hosts + } + + # Update mailname + echo '#{name}' > /etc/mailname + + # Restart networking and force new DHCP + if [ test -f /etc/init.d/hostname ]; then + /etc/init.d/hostname start || true + fi + + if [ test -f /etc/init.d/hostname.sh ]; then + /etc/init.d/hostname.sh start || true + fi + + if [ test -f /etc/init.d/networking ]; then + /etc/init.d/networking force-reload + fi + + if [ test -f /etc/init.d/network-manager ]; then + /etc/init.d/network-manager force-reload + fi + EOH end end - - def hardy? - os_version("hardy") - end - - def renew_dhcp - sudo("ifdown -a; ifup -a; ifup -a --allow=hotplug") - end - - private - - def init_package - machine.communicate.execute('cat /proc/1/comm') do |type, data| - return data.chomp if type == :stdout - end - end - - def os_version(name) - machine.communicate.test("[ `lsb_release -c -s` = #{name} ]") - end - - def systemd? - init_package == 'systemd' - end end end end