diff --git a/lib/linux_admin/hosts.rb b/lib/linux_admin/hosts.rb index f6a1dd1..9a3a2ea 100644 --- a/lib/linux_admin/hosts.rb +++ b/lib/linux_admin/hosts.rb @@ -1,5 +1,7 @@ module LinuxAdmin class Hosts + include Common + attr_accessor :filename attr_accessor :raw_lines attr_accessor :parsed_file @@ -36,6 +38,20 @@ def update_entry(address, hostname, comment = nil) end end + def hostname=(name) + if cmd?("hostnamectl") + run!(cmd('hostnamectl'), :params => ['set-hostname', name]) + else + File.write("/etc/hostname", name) + run!(cmd('hostname'), :params => {:file => "/etc/hostname"}) + end + end + + def hostname + result = run(cmd("hostname")) + result.success? ? result.output : nil + end + private def parse_file @parsed_file = [] diff --git a/spec/hosts_spec.rb b/spec/hosts_spec.rb index 0a4af2e..880a7c3 100644 --- a/spec/hosts_spec.rb +++ b/spec/hosts_spec.rb @@ -1,4 +1,5 @@ describe LinuxAdmin::Hosts do + TEST_HOSTNAME = "test-hostname" etc_hosts = "\n #Some Comment\n127.0.0.1\tlocalhost localhost.localdomain # with a comment\n127.0.1.1 my.domain.local" before do allow(File).to receive(:read).and_return(etc_hosts) @@ -50,4 +51,45 @@ expect(@instance.raw_lines).to eq(expected_array) end end + + describe "#hostname=" do + it "sets the hostname using hostnamectl when the command exists" do + spawn_args = [ + @instance.cmd('hostnamectl'), + :params => ['set-hostname', TEST_HOSTNAME] + ] + expect(@instance).to receive(:cmd?).with("hostnamectl").and_return(true) + expect(AwesomeSpawn).to receive(:run!).with(*spawn_args) + @instance.hostname = TEST_HOSTNAME + end + + it "sets the hostname with hostname when hostnamectl does not exist" do + spawn_args = [ + @instance.cmd('hostname'), + :params => {:file => "/etc/hostname"} + ] + expect(@instance).to receive(:cmd?).with("hostnamectl").and_return(false) + expect(File).to receive(:write).with("/etc/hostname", TEST_HOSTNAME) + expect(AwesomeSpawn).to receive(:run!).with(*spawn_args) + @instance.hostname = TEST_HOSTNAME + end + end + + describe "#hostname" do + let(:spawn_args) do + [@instance.cmd('hostname'), {}] + end + + it "returns the hostname" do + result = AwesomeSpawn::CommandResult.new("", TEST_HOSTNAME, nil, 0) + expect(AwesomeSpawn).to receive(:run).with(*spawn_args).and_return(result) + expect(@instance.hostname).to eq(TEST_HOSTNAME) + end + + it "returns nil when the command fails" do + result = AwesomeSpawn::CommandResult.new("", "", "An error has happened", 1) + expect(AwesomeSpawn).to receive(:run).with(*spawn_args).and_return(result) + expect(@instance.hostname).to be_nil + end + end end