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