class HieraTemplate

Templating handler object used by ERBReflective

Constants

DEFAULT_CONFIG

Public Class Methods

new(hiera_config = DEFAULT_CONFIG) click to toggle source
# File lib/hiera_template.rb, line 13
def initialize(hiera_config = DEFAULT_CONFIG)
  @scope = Facter.to_hash # Time consuming, do it once if possible!
  # Just so we can handle old facter references starting ::
  legacy = @scope.map { |k, v| ["::#{k}", v] }
  @scope.merge!(Hash[legacy])
  @hiera = Hiera.new(config: hiera_config)
end

Public Instance Methods

custom_file(path, owner: nil, group: nil, mode: nil) click to toggle source
# File lib/hiera_template.rb, line 64
def custom_file(path, owner: nil, group: nil, mode: nil)
  custom_out do |content|
    File.write(path, content)
    FileUtils.chown(owner, group, path) if owner || group
    FileUtils.chmod(mode, path) if mode
  end
end
custom_out(&block) click to toggle source

Methods used by ERBReflective to access hiera data See above, full content is not available until the template is rendered so we only stash the block references that we are given and call it later

# File lib/hiera_template.rb, line 35
def custom_out(&block)
  raise StandardError, 'custom_out requires a block argument' unless block_given?

  @blocks << block
end
hiera(key, default = nil) click to toggle source

If hiera does not exist we will try facter data in scope to unify the API

# File lib/hiera_template.rb, line 44
def hiera(key, default = nil)
  @hiera.lookup(key, nil, @scope) || @scope.dig(*key.split('.')) || default
end
hiera_array(key, default = nil) click to toggle source
# File lib/hiera_template.rb, line 52
def hiera_array(key, default = nil)
  @hiera.lookup(key, default, @scope, nil, :array)
end
hiera_hash(key, default = nil) click to toggle source
# File lib/hiera_template.rb, line 48
def hiera_hash(key, default = nil)
  @hiera.lookup(key, default, @scope, nil, :hash)
end
mkdir_p(path, owner: nil, group: nil, mode: nil) click to toggle source
# File lib/hiera_template.rb, line 56
def mkdir_p(path, owner: nil, group: nil, mode: nil)
  custom_out do |_|
    FileUtils.mkdir_p(path)
    FileUtils.chown_R(owner, group, path) if owner || group
    FileUtils.chmod_R(mode, path) if mode
  end
end
render(content) click to toggle source

Template render

# File lib/hiera_template.rb, line 22
def render(content)
  @blocks = []
  rendered = ERBReflective.new(content, nil, '-').result(self)
  return rendered unless @blocks.any?

  # See custom_out
  @blocks.each { |block| block.call(rendered) }
  true
end