puppethiera

Access hiera data from within a Puppet fact


As part of a custom Puppet fact I need to make a database query to fetch some dynamic data. This data will then be used by some resource elsewhere in the Puppet manifests. However to make the database connection I need to be able to read some encrypted data stored within hiera (a password). However I'm not sure how to access this data from within Ruby. Perhaps it is not even possible since the fact will run agent side whilst hiera, used when compiling the catalogue, is run server side. However I am currently making the assumption that I can access hiera using something like the following:

Facter.add(:metadata) do
  setcode do
    database_password = Hiera.lookup('profile::runner::agent::database_password')
    
    # make the DB connetion and run the query...
    make_database_query_and_return_result_as_hash(database_password, Facter.value(:hostname))
  end
end

Is it possible to access hiera data from within a fact this way? At present there is a long feedback loop to test this (something we're working on to reduce), so I'd appreciate being pointed in the right direction.


Solution

  • Facter runs on the target node at the beginning of a Puppet run, it sends the facts to the Puppet server which is where any hiera lookups are done. So that will never work because the fact is run before any hiera lookups and on a different machine.

    The way to do this is not to do it as a fact but as a custom function, the custom function is ruby code that is run on the Puppet server at the time of catalog the compilation. https://puppet.com/docs/puppet/7/lang_write_functions_in_puppet.html

    And if you're querying the Puppet DB for information you're already on the localhost so authentication should be easy. https://puppet.com/docs/puppetdb/6/api/query/tutorial.html

    This forge module might do what you want https://forge.puppet.com/modules/dalen/puppetdbquery