0

I am looking for a way to determine the interface associated to a given IP. Right now I have the opposite where I can return the IP for an interface.

def ipv4_for_interface(i)
  return unless node['network']['interfaces'].has_key?(i)
  addr, data = node['network']['interfaces'][i]['addresses'].find { |x| x[1]['family'] == 'inet' }
  addr
end

For my specific purpose I could do some really dumb iterating through an array and do pattern matching, but I'd like to know how to do it generally.

The internet is full of examples of how to do the opposite of what I'm looking for.

My current hack is this and I really don't like it.

def first_matching_ipv4(match_method)
  all = all_matching_ipv4(match_method)
  return all[0] unless all.empty?
end

def first_private_ipv4
  first_matching_ipv4(:private_ipv4?)
end


ruby_block 'get private' do
  block do
    node.default['return_val']=$(ifconfig | grep -B1 "inet addr:#{first_private_ipv4}" | awk '$1!="inet" && $1!="--" {print $1}')
  end
end

ruby_block 'get public' do
  block do
    node.default['return_val']=$(ifconfig | grep -B1 "inet addr:#{first_public_ipv4}" | awk '$1!="inet" && $1!="--" {print $1}')
 end
end
Brando__
  • 365
  • 6
  • 24
  • The solution below had a really bizarre effect that I can't explain. It would always work in the chef-shell, but very rarely (once out of 20+ machines) work in a recipe. The alternative solution I ended up using can be found here http://stackoverflow.com/questions/43773141/ruby-return-top-level-hash-key-if-value-recursively-contains-string – Brando__ May 05 '17 at 20:49

1 Answers1

2

Something like this:

def interface_for_ipv4(addr)
  node['network']['interfaces'].find do |interface, data|
    data['addresses'][addr]
  end.first
end
coderanger
  • 52,400
  • 4
  • 52
  • 75
  • This works perfectly. Thank you. MUCH better than the garbage I threw together. – Brando__ Apr 27 '17 at 02:44
  • I've tried going through this bit by bit in the chef-shell and googling, but how is this actually working? I don't follow on the variable assignment. I vaguely get that it's iterating through the ohai hashes until something finally returns that returns true, per the enumerable#find method, but to what and how interface and data is assigned I don't follow. I'm not familiar with what the [ ] method notation is doing either – Brando__ Apr 27 '17 at 06:24