Update stdlib
[mirror/dsa-puppet.git] / 3rdparty / modules / stdlib / lib / puppet / parser / functions / validate_ip_address.rb
1 module Puppet::Parser::Functions
2
3   newfunction(:validate_ip_address, :doc => <<-ENDHEREDOC
4     Validate that all values passed are valid IP addresses,
5     regardless they are IPv4 or IPv6
6     Fail compilation if any value fails this check.
7     The following values will pass:
8     $my_ip = "1.2.3.4"
9     validate_ip_address($my_ip)
10     validate_ip_address("8.8.8.8", "172.16.0.1", $my_ip)
11
12     $my_ip = "3ffe:505:2"
13     validate_ip_address(1)
14     validate_ip_address($my_ip)
15     validate_ip_address("fe80::baf6:b1ff:fe19:7507", $my_ip)
16
17     The following values will fail, causing compilation to abort:
18     $some_array = [ 1, true, false, "garbage string", "3ffe:505:2" ]
19     validate_ip_address($some_array)
20     ENDHEREDOC
21   ) do |args|
22
23     require "ipaddr"
24     rescuable_exceptions = [ ArgumentError ]
25
26     function_deprecation([:validate_ip_address, 'This method is deprecated, please use the stdlib validate_legacy function, with Stdlib::Compat::Ip_address. There is further documentation for validate_legacy function in the README.'])
27
28     if defined?(IPAddr::InvalidAddressError)
29       rescuable_exceptions << IPAddr::InvalidAddressError
30     end
31
32     unless args.length > 0 then
33       raise Puppet::ParseError, ("validate_ip_address(): wrong number of arguments (#{args.length}; must be > 0)")
34     end
35
36     args.each do |arg|
37       unless arg.is_a?(String)
38         raise Puppet::ParseError, "#{arg.inspect} is not a string."
39       end
40
41       begin
42         unless IPAddr.new(arg).ipv4? or IPAddr.new(arg).ipv6?
43           raise Puppet::ParseError, "#{arg.inspect} is not a valid IP address."
44         end
45       rescue *rescuable_exceptions
46         raise Puppet::ParseError, "#{arg.inspect} is not a valid IP address."
47       end
48     end
49
50   end
51
52 end