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.
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'})
20 raise ArgumentError, 'Wrong number of arguments. 1 or 2 arguments should be provided.' unless args.length >= 1
24 if args[0].start_with?('http://', 'https://')
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}"
39 contents = OpenURI.open_uri(url, :http_basic_authentication => [username, password])
40 rescue OpenURI::HTTPError => err
42 warning("Can't load '#{url}' HTTP Error Code: '#{res.status[0]}'")
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]
49 warning("Can't load '#{args[0]}' File does not exist!")
52 rescue StandardError => e
53 raise e unless args[1]