4 module Puppet::Parser::Functions
5 newfunction(:loadyaml, :type => :rvalue, :arity => -2, :doc => <<-'DOC') do |args|
7 Load a YAML file containing an array, string, or hash, and return the data
8 in the corresponding native data type.
10 The first parameter can be a file path or a URL.
11 The second parameter is the default value. It will be returned if the file
12 was not found or could not be parsed.
14 @return [Array|String|Hash]
15 The data stored in the YAML file, the type depending on the type of data that was stored.
17 @example Example Usage:
18 $myhash = loadyaml('/etc/puppet/data/myhash.yaml')
19 $myhash = loadyaml('https://example.local/my_hash.yaml')
20 $myhash = loadyaml('https://username:password@example.local/my_hash.yaml')
21 $myhash = loadyaml('no-file.yaml', {'default' => 'value'})
24 raise ArgumentError, 'Wrong number of arguments. 1 or 2 arguments should be provided.' unless args.length >= 1
28 if args[0].start_with?('http://', 'https://')
31 if (match = args[0].match(%r{(http\://|https\://)(.*):(.*)@(.*)}))
32 # If URL is in the format of https://username:password@example.local/my_hash.yaml
33 protocol, username, password, path = match.captures
34 url = "#{protocol}#{path}"
35 elsif (match = args[0].match(%r{(http\:\/\/|https\:\/\/)(.*)@(.*)}))
36 # If URL is in the format of https://username@example.local/my_hash.yaml
37 protocol, username, path = match.captures
38 url = "#{protocol}#{path}"
43 contents = OpenURI.open_uri(url, :http_basic_authentication => [username, password])
44 rescue OpenURI::HTTPError => err
46 warning("Can't load '#{url}' HTTP Error Code: '#{res.status[0]}'")
49 YAML.safe_load(contents) || args[1]
50 elsif File.exists?(args[0]) # rubocop:disable Lint/DeprecatedClassMethods : Changing to .exist? breaks the code
51 YAML.load_file(args[0]) || args[1]
53 warning("Can't load '#{args[0]}' File does not exist!")
56 rescue StandardError => e
57 raise e unless args[1]