summaryrefslogtreecommitdiff
path: root/lib/puppet/parser/functions/couchdblookup.rb
blob: 2e1545e3afb624912f56c13f9ca2e4ca869a2053 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#
# A basic function to retrieve data in couchdb
#


module Puppet::Parser::Functions
  newfunction(:couchdblookup, :type => :rvalue) do |args|
    require 'json'
    require 'open-uri'

    url = args[0]
    key = args[1]

    raise Puppet::ParseError, ("couchdblookup(): wrong number of arguments (#{args.length}; must be == 2)") if args.length != 2

    begin
      json = JSON.parse(open(URI.parse(url)).read)
    rescue OpenURI::HTTPError => error
      raise Puppet::ParseError, "couchdblookup(): fetching URL #{url} failed with status #{error.message}"
    end

    result = nil
    if json.has_key?("rows") and json['total_rows'] > 0 and json['rows'][0].has_key?(key)
      result = Array.new
      json['rows'].each do |x|
        result.push(x[key])
      end
    else
      if json.has_key?(key)
        result = json[key]
      end
    end

    result or raise Puppet::ParseError, "couchdblookup(): key '#{key}' not found in JSON object !"

  end
end