diff --git a/plugins/guests/arch/cap/change_host_name.rb b/plugins/guests/arch/cap/change_host_name.rb index be0fd3079..e642129c0 100644 --- a/plugins/guests/arch/cap/change_host_name.rb +++ b/plugins/guests/arch/cap/change_host_name.rb @@ -3,12 +3,19 @@ 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("hostnamectl set-hostname #{name}") - comm.sudo("sed -i 's@^\\(127[.]0[.]0[.]1[[:space:]]\\+\\)@\\1#{name} @' /etc/hosts") - end + comm = machine.communicate + + if !comm.test("hostname | grep -w '#{name}'", sudo: true) + basename = name.split(".", 2)[0] + comm.sudo <<-EOH +hostnamectl set-hostname '#{name}' + +# Remove comments and blank lines from /etc/hosts +sed -i'' -e 's/#.*$//' -e '/^$/d' /etc/hosts + +# Prepend ourselves to /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/arch/cap/change_host_name_test.rb b/test/unit/plugins/guests/arch/cap/change_host_name_test.rb index c8cf9c1ce..e296caa0a 100644 --- a/test/unit/plugins/guests/arch/cap/change_host_name_test.rb +++ b/test/unit/plugins/guests/arch/cap/change_host_name_test.rb @@ -9,29 +9,30 @@ describe "VagrantPlugins::GuestArch::Cap::ChangeHostName" do end let(:machine) { double("machine") } - let(:communicator) { VagrantTests::DummyCommunicator::Communicator.new(machine) } + let(:comm) { VagrantTests::DummyCommunicator::Communicator.new(machine) } before do - allow(machine).to receive(:communicate).and_return(communicator) + allow(machine).to receive(:communicate).and_return(comm) end after do - communicator.verify_expectations! + comm.verify_expectations! end describe ".change_host_name" do - let(:hostname) { "example.com" } + let(:hostname) { "banana-rama.example.com" } it "sets the hostname" do - communicator.stub_command("sudo hostname | grep '#{hostname}'", exit_code: 1) - communicator.expect_command("hostnamectl set-hostname #{hostname}") + comm.stub_command("hostname | grep -w '#{hostname}'", exit_code: 1) + described_class.change_host_name(machine, hostname) + expect(comm.received_commands[1]).to match(/hostnamectl set-hostname '#{hostname}'/) end it "does not change the hostname if already set" do - communicator.stub_command("sudo hostname | grep '#{hostname}'", exit_code: 0) + comm.stub_command("hostname | grep -w '#{hostname}'", exit_code: 0) described_class.change_host_name(machine, hostname) - expect(communicator.received_commands.size).to eq(1) + expect(comm.received_commands.size).to eq(1) end end end