Class: Hiera::Backend::Regex_backend

Inherits:
Object
  • Object
show all
Defined in:
lib/hiera/backend/regex_backend.rb

Instance Method Summary collapse

Constructor Details

#initialize(cache = nil) ⇒ Regex_backend

TODO: Support JSON or YAML format and initialize accordingly



8
9
10
11
# File 'lib/hiera/backend/regex_backend.rb', line 8

def initialize(cache=nil)
   require 'yaml'
   @cache = cache || Filecache.new
end

Instance Method Details

#datasourcefiles(scope) ⇒ Object



61
62
63
64
65
66
67
68
69
# File 'lib/hiera/backend/regex_backend.rb', line 61

def datasourcefiles(scope)
  datadir = Backend.datadir(:regex, scope)
  datasources(scope) do |source|
    file = Backend.datafile(:regex, scope, source, :regex)
    if file
      yield(file)
    end
  end
end

#datasources(scope) ⇒ Object



47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/hiera/backend/regex_backend.rb', line 47

def datasources(scope)
  datadir = Backend.datadir(:regex, scope)
  Config[:hierarchy].flatten.map do |source|
    # We only support data sources that end in a key.  Keys found
    # in the middle of a datasource's name are impossible to support since
    # standard file names do not do well containing regular experssion patterns
    if source =~ /\}$/
      # We need to strip out the ending key's %{::} characters so that they do not
      # get interpolated when we call parse_string
      yield(Backend.parse_string(source.gsub(/%\{:*([^\{]*)\}$/, '\1'), scope))
    end
  end
end

#lookup(key, scope, order_override, resolution_type) ⇒ Object

TODO: Support multiple resolution_types, currently only supports :priority



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
39
40
41
42
43
44
45
# File 'lib/hiera/backend/regex_backend.rb', line 14

def lookup(key, scope, order_override, resolution_type)
  answer = nil
  datasourcefiles(scope) do |source|
    scope_key = File.basename(source, ".regex")
    scope_key = "::#{scope_key}" if ! scope[scope_key]
    if ! scope[scope_key]
      Hiera.debug("Could not find key #{scope_key} within scope, skipping check for source #{source}")
      next
    end
    Hiera.debug("Checking #{source} for #{scope_key} regex matching #{scope[scope_key]}")

    # TODO: Add support for more than just YAML format
    data = YAML.load(@cache.read(source))

    next if ! data
    next if data.empty?

    lineno = 0
    data.each do |item|
      lineno = lineno + 1
      item.each_key do |regex_key|
        if scope[scope_key] =~ /#{regex_key}/ and item[regex_key][key]
          Hiera.debug("#{scope_key} with value of '#{scope[scope_key]}' matched regex /#{regex_key}/ at #{source}:#{lineno}")
          answer = Backend.parse_string(item[regex_key][key], scope)
          break
        end
      end
      break if answer
    end
  end
  return answer
end