Merge pull request #11996 from soapy1/sles_change_host_name

Don't use hostnamectl if not on system
This commit is contained in:
Sophia Castellarin 2020-10-28 15:08:50 -05:00 committed by GitHub
commit 1f9347dd5f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 47 additions and 11 deletions

View File

@ -1,22 +1,43 @@
require_relative '../../linux/cap/change_host_name'
require 'vagrant/util/guest_hosts'
require 'vagrant/util/guest_inspection'
module VagrantPlugins
module GuestSUSE
module Cap
class ChangeHostName
extend VagrantPlugins::GuestLinux::Cap::ChangeHostName
def self.change_host_name?(comm, name)
basename = name.split(".", 2)[0]
!comm.test("test \"$(hostnamectl --static status)\" = \"#{basename}\"", sudo: false)
end
extend Vagrant::Util::GuestInspection::Linux
extend Vagrant::Util::GuestHosts::Linux
def self.change_name_command(name)
def self.change_host_name(machine, name)
comm = machine.communicate
basename = name.split(".", 2)[0]
return <<-EOH.gsub(/^ {14}/, "")
hostnamectl set-hostname '#{basename}'
echo #{name} > /etc/HOSTNAME
EOH
network_with_hostname = machine.config.vm.networks.map {|_, c| c if c[:hostname] }.compact[0]
if network_with_hostname
replace_host(comm, name, network_with_hostname[:ip])
else
add_hostname_to_loopback_interface(comm, name)
end
if hostnamectl?(comm)
if !comm.test("test \"$(hostnamectl --static status)\" = \"#{basename}\"", sudo: false)
cmd = <<-EOH.gsub(/^ {14}/, "")
hostnamectl set-hostname '#{basename}'
echo #{name} > /etc/HOSTNAME
EOH
comm.sudo(cmd)
end
else
if !comm.test("hostname -f | grep '^#{name}$'", sudo: false)
cmd = <<-EOH.gsub(/^ {14}/, "")
echo #{name} > /etc/HOSTNAME
hostname '#{basename}'
EOH
comm.sudo(cmd)
end
end
end
end
end

View File

@ -15,6 +15,7 @@ describe "VagrantPlugins::GuestSUSE::Cap::ChangeHostName" do
before do
allow(machine).to receive(:communicate).and_return(comm)
allow(cap).to receive(:hostnamectl?).and_return(true)
end
after do
@ -45,6 +46,20 @@ describe "VagrantPlugins::GuestSUSE::Cap::ChangeHostName" do
cap.change_host_name(machine, name)
expect(comm.received_commands.size).to eq(3)
end
context "hostnamectl is not present" do
before do
allow(cap).to receive(:hostnamectl?).and_return(false)
end
it "sets the hostname" do
comm.stub_command("hostname -f | grep '^#{name}$'", exit_code: 1)
cap.change_host_name(machine, name)
expect(comm.received_commands[2]).to match(/echo #{name} > \/etc\/HOSTNAME/)
expect(comm.received_commands[2]).to match(/hostname '#{basename}'/)
end
end
end
end
end