Skip to content

Instantly share code, notes, and snippets.

@soudaburger
Last active August 24, 2017 14:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save soudaburger/e253bdce191c731491581df0b0f99234 to your computer and use it in GitHub Desktop.
Save soudaburger/e253bdce191c731491581df0b0f99234 to your computer and use it in GitHub Desktop.
# File Backend for Hiera
Puppet::Functions.create_function(:'file_backend', Puppet::Functions::InternalFunction) do
dispatch :file_backend do
scope_param
repeated_param 'String', :paths
end
dispatch :file_backend_array do
scope_param
repeated_param 'Array[String]', :paths
end
def file_backend_array(scope, array)
file_backend(scope, *array)
end
def file_backend(scope, *args)
searchpath = nil
args.each do |file|
found = Puppet::Parser::Files.find_file(file, scope.compiler.environment)
if found && Puppet::FileSystem.exist?(found)
# I would like to actually read and return the contents of the file here.
# return found
end
end
nil
end
version: 5
defaults:
datadir: hieradata
data_hash: yaml_data
hierarchy:
- name: "File Backend Lookup (Default)"
data_hash: 'file_backend'
paths:
- "/tmp/hieradata/environments/%{::environment}/files/mymodule"
class mymodule() {
# This is where I would like to make the magic happen.
# I simply want puppet to do a file-lookup and return
# the content of the file found in HIERA.
# This path to the file would be appended to the 'datadir'
# and 'path(s)' defined in the relevant hiera.yaml
file { '/tmp/file1.txt':
ensure => present,
content => lookup('/path/to/source/file1.txt')
}
}
@hlindberg
Copy link

  • You need an additional function to transform a pathname with dots to one where they are escaped. But skip that problem first and only test it with a path that does not contain any dots
  • Your backend function does not have the correct kind, and signature
  • Your backend function should not have a 'scope_param' in the dispatcher
  • Use Puppet::Filesystem.read(path) to read the content of the file referenced by 'path'
  • The backend function receives a path in the options hash - that path is guaranteed to exist - all non existing paths are simply skipped by hiera (see the linked docs how it works). Thus, you do not need to use any of the find file, etc. You can use relative paths in the hiera.yaml config and hiera will figure it out (see the docs).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment