问题
I am trying to load the contents of a json file and assign them to variables. My json file looks like this :
{ "master":{ "key1":"value1", "key2":"value2", "key3":"value3" } }
On my local machine, I was able to use the following manifest to load the json file and parse it ; it worked just fine.
$master_hash=loadjson('some_file.json')
$key1=$master_hash['master']['key1']
$key2=$master_hash['master']['key2']
$key3=$master_hash['master']['key3']
However, when I move it to the Puppet master, this fails as it looks for the json file on the Puppet master ! In my earlier request, Puppet : How to load file from agent
, I was told to use a function and that worked fine for one fact, but in this case I need to generate a number of them depending on the contents of the json file. How can I achieve this ?
回答1:
Functions like loadjson()
execute on the machine which is compiling the catalog. In the majority of cases this means that the function executes on the master. Since some_file.json doesn't exist on the master it won't load the file.
If you want to transfer information from the agent to the master then you need to use a fact to do so. Facts are synced to the agent machine and executed at the start of the run, and their values are sent back to the master.
The answer to your previous question was a good base, but I'll expand on it a bit here:
# module_name/lib/facter/master_hash.rb
require 'json'
Facter.add(:master_hash) do
setcode do
# return content of foo as a string
f = File.read('/path/to/some_file.json')
master_hash = JSON.parse(f)
master_hash
end
end
The last line of the setcode block gets returned as the value of the fact. In this case it would expose a $::master_hash
fact which would contain a hash from the parsed json.
来源:https://stackoverflow.com/questions/43808941/puppet-how-to-load-file-from-agent-part-2