guests/suse: Change host name in one command

This commit is contained in:
Seth Vargo 2016-06-06 10:38:02 -04:00
parent fb90c67a49
commit b091f4fe82
No known key found for this signature in database
GPG Key ID: 905A90C2949E8787
2 changed files with 55 additions and 7 deletions

View File

@ -3,14 +3,22 @@ module VagrantPlugins
module Cap module Cap
class ChangeHostName class ChangeHostName
def self.change_host_name(machine, name) def self.change_host_name(machine, name)
machine.communicate.tap do |comm| comm = machine.communicate
# Only do this if the hostname is not already set
if !comm.test("sudo hostname | grep '#{name}'")
comm.sudo("echo #{name} > /etc/HOSTNAME")
comm.sudo("hostname #{name}")
comm.sudo("sed -i 's@^\\(127[.]0[.]0[.]1[[:space:]]\\+\\)@\\1#{name} #{name.split('.')[0]} @' /etc/hosts") if !comm.test("hostname -f | grep -w '#{name}'", sudo: false)
end basename = name.split(".", 2)[0]
comm.sudo <<-EOH.gsub(/^ {14}/, '')
echo '#{name}' > /etc/HOSTNAME
hostname '#{name}'
# 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 end
end end

View File

@ -0,0 +1,40 @@
require_relative "../../../../base"
describe "VagrantPlugins::GuestSUSE::Cap::ChangeHostName" do
let(:caps) do
VagrantPlugins::GuestSUSE::Plugin
.components
.guest_capabilities[:suse]
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 '#{name}'/)
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