Puppet Function: ip_for_network

Defined in:
lib/puppet/parser/functions/ip_for_network.rb
Function type:
Ruby 3.x API

Overview

ip_for_network()Any

Returns an ip address for the given network in cidr notation

ip_for_network(“127.0.0.0/24”) => 127.0.0.1

Returns:

  • (Any)


5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/puppet/parser/functions/ip_for_network.rb', line 5

newfunction(:ip_for_network, :type => :rvalue, :doc => <<-EOS
Returns an ip address for the given network in cidr notation

ip_for_network("127.0.0.0/24") => 127.0.0.1
  EOS
) do |args| 
  addresses_in_range = [] 

  range = IPAddr.new(args[0])
  facts = compiler.node.facts.values
  ip_addresses = facts.select { |key, value| key.match /^ipaddress/ }

  ip_addresses.each do |pair|
    key = pair[0]
    string_address = pair[1]
    ip_address = IPAddr.new(string_address)
    if range.include?(ip_address)
      addresses_in_range.push(string_address)
    end
  end

  # TODO don't be a dork dork with the return
  # handle multiple values!
  return addresses_in_range.first
end