diff --git a/plugins/guests/slackware/cap/change_host_name.rb b/plugins/guests/slackware/cap/change_host_name.rb index 07976725f..d16bfabd0 100644 --- a/plugins/guests/slackware/cap/change_host_name.rb +++ b/plugins/guests/slackware/cap/change_host_name.rb @@ -3,14 +3,25 @@ module VagrantPlugins module Cap class ChangeHostName def self.change_host_name(machine, name) - machine.communicate.tap do |comm| - # Only do this if the hostname is not already set - if !comm.test("sudo hostname | grep '#{name}'") - comm.sudo("chmod o+w /etc/hostname") - comm.sudo("echo #{name} > /etc/hostname") - comm.sudo("chmod o-w /etc/hostname") - comm.sudo("hostname -F /etc/hostname") - end + comm = machine.communicate + + if !comm.test("hostname -f | grep -w '#{name}'", sudo: false) + basename = name.split(".", 2)[0] + comm.sudo <<-EOH.gsub(/^ {14}/, '') + # Set the hostname + chmod o+w /etc/hostname + echo '#{name}' > /etc/hostname + chmod o-w /etc/hostname + hostname -F /etc/hostname + + # 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 + } + EOH end end end diff --git a/test/unit/plugins/guests/slackware/cap/change_host_name_test.rb b/test/unit/plugins/guests/slackware/cap/change_host_name_test.rb new file mode 100644 index 000000000..2c128fc61 --- /dev/null +++ b/test/unit/plugins/guests/slackware/cap/change_host_name_test.rb @@ -0,0 +1,40 @@ +require_relative "../../../../base" + +describe "VagrantPlugins::GuestSlackware::Cap::ChangeHostName" do + let(:caps) do + VagrantPlugins::GuestSlackware::Plugin + .components + .guest_capabilities[:slackware] + end + + let(:machine) { double("machine") } + let(:comm) { VagrantTests::DummyCommunicator::Communicator.new(machine) } + + before do + allow(machine).to receive(:communicate).and_return(comm) + end + + after do + comm.verify_expectations! + end + + describe ".change_host_name" do + let(:cap) { caps.get(:change_host_name) } + + let(:name) { "banana-rama.example.com" } + + it "sets the hostname" do + comm.stub_command("hostname -f | grep -w '#{name}'", exit_code: 1) + + cap.change_host_name(machine, name) + expect(comm.received_commands[1]).to match(/echo '#{name}' > \/etc\/hostname/) + expect(comm.received_commands[1]).to match(/hostname -F \/etc\/hostname/) + end + + it "does not change the hostname if already set" do + comm.stub_command("hostname -f | grep -w '#{name}'", exit_code: 0) + cap.change_host_name(machine, name) + expect(comm.received_commands.size).to eq(1) + end + end +end