Suggest different variables to use if we want to tunnel both v4 and v6
[mirror/dsa-puppet.git] / 3rdparty / modules / stdlib / lib / puppet / parser / functions / loadjson.rb
1 #
2 # loadjson.rb
3 #
4
5 module Puppet::Parser::Functions
6   newfunction(:loadjson, :type => :rvalue, :arity => -2, :doc => <<-'DOC') do |args|
7     Load a JSON file containing an array, string, or hash, and return the data
8     in the corresponding native data type.
9     The first parameter can be a file path or a URL.
10     The second parameter is the default value. It will be returned if the file
11     was not found or could not be parsed.
12
13     For example:
14
15         $myhash = loadjson('/etc/puppet/data/myhash.json')
16         $myhash = loadjson('https://example.local/my_hash.json')
17         $myhash = loadjson('https://username:password@example.local/my_hash.json')
18         $myhash = loadjson('no-file.json', {'default' => 'value'})
19   DOC
20
21     raise ArgumentError, 'Wrong number of arguments. 1 or 2 arguments should be provided.' unless args.length >= 1
22     require 'open-uri'
23     begin
24       if args[0].start_with?('http://', 'https://')
25         username = ''
26         password = ''
27         if (match = args[0].match(%r{(http\://|https\://)(.*):(.*)@(.*)}))
28           # If URL is in the format of https://username:password@example.local/my_hash.yaml
29           protocol, username, password, path = match.captures
30           url = "#{protocol}#{path}"
31         elsif (match = args[0].match(%r{(http\:\/\/|https\:\/\/)(.*)@(.*)}))
32           # If URL is in the format of https://username@example.local/my_hash.yaml
33           protocol, username, path = match.captures
34           url = "#{protocol}#{path}"
35         else
36           url = args[0]
37         end
38         begin
39           contents = OpenURI.open_uri(url, :http_basic_authentication => [username, password])
40         rescue OpenURI::HTTPError => err
41           res = err.io
42           warning("Can't load '#{url}' HTTP Error Code: '#{res.status[0]}'")
43           args[1]
44         end
45         PSON.load(contents) || args[1]
46       elsif File.exists?(args[0]) # rubocop:disable Lint/DeprecatedClassMethods : Changing to .exist? breaks the code
47         content = File.read(args[0])
48         PSON.load(content) || args[1]
49       else
50         warning("Can't load '#{args[0]}' File does not exist!")
51         args[1]
52       end
53     rescue StandardError => e
54       raise e unless args[1]
55       args[1]
56     end
57   end
58 end