Use content of a file as a variable with Puppet

July 16, 2022 

Every now and then a need to use the content of a file as a variable on an agent node arises. Here's one way to do it with the help of a custom fact.

First create a custom fact on the puppet server:

Facter.add(:my_file_content) do
  setcode do
    path = "/path/to/my_file"
    File.read(path) if File.exist?(path)
   end
end

You can confine this to restrict it to be available only on selected nodes, for example:

Facter.add(:my_file_content) do
  confine :hostname => [ :'my_first_node', :'my_second_node']
  setcode do
    path = "/path/to/my_file"
    File.read(path) if File.exist?(path)
   end
end

Next use this custom fact to load the file content into a variable:

$my_variable=$facts['my_file_content']

You can now split(), join(), regexp(), strip() etc. it to your hearts content.

That's it. As always, be sensible with the possible security implications.

Samuli Seppänen
Petri Lammi
Author archive
menucross-circle