Skip to content

Instantly share code, notes, and snippets.

@glarizza
Created December 7, 2013 02:15
Show Gist options
  • Save glarizza/7836514 to your computer and use it in GitHub Desktop.
Save glarizza/7836514 to your computer and use it in GitHub Desktop.
# <modulepath>/extract_backend/lib/hiera/backend/extract_backend.rb
require 'yaml'
class Hiera
module Backend
class Extract_backend
def lookup(key, scope, order_override, resolution_type)
# Start your work here...
Hiera.debug "We're in the lookup method!"
# Use Backend.datasources to iterate through all data sources
Backend.datasources(scope, order_override) do |source|
# Get the path to the file we want to inspect by calling Backend.datafile
# on the :extract_backend method and passing it the scope, source and file extension
# This will query the hiera.yaml config file, look for the 'extract_backend' section,
# and populate the path based on the values you pass.
path = Backend.datafile(:extract, scope, source, 'yaml')
next unless path
Hiera.debug "Key: #{key} Path: #{path}"
# Actually call the extract method below with the key and the path that
# you retrieved in the previous step - it should return an answer
value = extract(key, path)
Hiera.debug "Your value is: #{value}"
# Once you have a value from the etract method, we need to call Backend.parse_answer
# with the value from the previous lookup and scope object - this will parse any
# 'interpolation tokens' (e.g. %{environment}) out and replace it with actual values
parsed_answer = Backend.parse_answer(value, scope)
Hiera.debug "The parsed answer is: #{parsed_answer}"
# FINALLY, check the resolution_type and return an answer. If it's a priority
# lookup, we'll just return the first answer we have. If it's :array or :hash,
# then handle it accordingly...
case resolution_type
when :array
Hiera.debug "Resolution type: array"
@answer ||= []
@answer << parsed_answer
when :hash
Hiera.debug "Resolution type: hash"
@answer ||= {}
@answer = parsed_answer.merge @answer
else
Hiera.debug "Resolution type: priority"
# This means it's a priority lookup
# We need the 'break' to jump out of the loop
@answer = parsed_answer
break
end
Hiera.debug "The @answer is: #{@answer}"
@answer
end
@answer
end
def extract(key, path)
# This is going to be a method VERY SIMILAR to the extract function we wrote
# previously.
datafile = YAML.load_file(path)
# Handle any exception cases here
# (i.e. if the datafile is empty or doesn't have the key we want)
return unless datafile
return if datafile.empty?
return unless datafile.include?(key)
# Return the value
return datafile[key]
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment