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 / loadyaml.rb
1 #
2 # loadyaml.rb
3 #
4 module Puppet::Parser::Functions
5   newfunction(:loadyaml, :type => :rvalue, :arity => -2, :doc => <<-'DOC') do |args|
6     Load a YAML file containing an array, string, or hash, and return the data
7     in the corresponding native data type.
8     The first parameter can be a file path or a URL.
9     The second parameter is the default value. It will be returned if the file
10     was not found or could not be parsed.
11
12     For example:
13
14         $myhash = loadyaml('/etc/puppet/data/myhash.yaml')
15         $myhash = loadyaml('https://example.local/my_hash.yaml')
16         $myhash = loadyaml('https://username:password@example.local/my_hash.yaml')
17         $myhash = loadyaml('no-file.yaml', {'default' => 'value'})
18   DOC
19
20     raise ArgumentError, 'Wrong number of arguments. 1 or 2 arguments should be provided.' unless args.length >= 1
21     require 'yaml'
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         YAML.safe_load(contents) || args[1]
46       elsif File.exists?(args[0]) # rubocop:disable Lint/DeprecatedClassMethods : Changing to .exist? breaks the code
47         YAML.load_file(args[0]) || args[1]
48       else
49         warning("Can't load '#{args[0]}' File does not exist!")
50         args[1]
51       end
52     rescue StandardError => e
53       raise e unless args[1]
54       args[1]
55     end
56   end
57 end