Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions lib/linux_admin/hosts.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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])
Expand Down
44 changes: 44 additions & 0 deletions spec/hosts_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down