]> git.openstreetmap.org Git - chef.git/blob - cookbooks/networking/libraries/ipaddresses.rb
8efba26de195624e0196e5d61ae9a193ea8f4330
[chef.git] / cookbooks / networking / libraries / ipaddresses.rb
1 require "ipaddr"
2
3 module OpenStreetMap
4   module Mixin
5     module IPAddresses
6       class Address
7         attr_reader :address, :prefix, :gateway, :network, :netmask
8
9         def initialize(address)
10           @address = address[:public_address] || address[:address]
11           @prefix = address[:prefix]
12           @gateway = address[:gateway]
13
14           ip = IPAddr.new(address[:address]).mask(address[:prefix])
15
16           @network = ip.to_s
17           @netmask = ip.netmask
18         end
19
20         def to_s
21           address
22         end
23
24         def subnet
25           "#{@network}/#{@prefix}"
26         end
27       end
28
29       def ipaddresses(role: nil, family: nil)
30         interfaces(:role => role).each_with_object([]) do |interface, addresses|
31           addresses << Address.new(interface[:inet]) if interface[:inet] && (family.nil? || family == :inet)
32           addresses << Address.new(interface[:inet6]) if interface[:inet6] && (family.nil? || family == :inet6)
33         end
34       end
35
36       def internal_ipaddress(family: nil)
37         ipaddresses(:role => :internal, :family => family).first
38       end
39
40       def external_ipaddress(family: nil)
41         ipaddresses(:role => :external, :family => family).first
42       end
43     end
44   end
45 end
46
47 Chef::Node.include(OpenStreetMap::Mixin::IPAddresses)