diff --git a/lib/linux_admin/hosts.rb b/lib/linux_admin/hosts.rb index 9a3a2ea..796e466 100644 --- a/lib/linux_admin/hosts.rb +++ b/lib/linux_admin/hosts.rb @@ -38,6 +38,20 @@ def update_entry(address, hostname, comment = nil) end end + # Updates the IP address associated with the entry specified by the hostname + # or inserts a new row in the file if there is no entry for that name + # + # @param hostname [String] the hostname used to find the record to update + # @param ip [String] the new address to use for the record + def update_ip_for_hostname(host, ip) + line_num = @parsed_file.find_path(host).first + if line_num + @parsed_file[line_num][:address] = ip + else + update_entry(ip, host) + end + end + def hostname=(name) if cmd?("hostnamectl") run!(cmd('hostnamectl'), :params => ['set-hostname', name]) diff --git a/spec/hosts_spec.rb b/spec/hosts_spec.rb index 880a7c3..1513a4a 100644 --- a/spec/hosts_spec.rb +++ b/spec/hosts_spec.rb @@ -32,6 +32,50 @@ end end + describe "#update_ip_for_hostname" do + it "updates an existing entry" do + expected_hash = [ + {:blank => true}, + {:comment => "Some Comment"}, + {:address => "127.0.0.1", + :hosts => [ + "localhost", + "localhost.localdomain" + ], + :comment => "with a comment" + }, + {:address => "192.168.1.10", + :hosts => ["my.domain.local"] + } + ] + @instance.update_ip_for_hostname("my.domain.local", "192.168.1.10") + expect(@instance.parsed_file).to eq(expected_hash) + end + + it "creates a new entry if none match" do + expected_hash = [ + {:blank => true}, + {:comment => "Some Comment"}, + {:address => "127.0.0.1", + :hosts => [ + "localhost", + "localhost.localdomain" + ], + :comment => "with a comment" + }, + {:address => "127.0.1.1", + :hosts => ["my.domain.local"] + }, + {:address => "192.168.1.10", + :hosts => ["new.domain.local"], + :comment => nil + } + ] + @instance.update_ip_for_hostname("new.domain.local", "192.168.1.10") + expect(@instance.parsed_file).to eq(expected_hash) + end + end + describe "#save" do before do allow(File).to receive(:write)