Puppet:如何从代理加载文件 - 第 2 部分 [英] Puppet : How to load file from agent - Part 2

查看:67
本文介绍了Puppet:如何从代理加载文件 - 第 2 部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试加载 json 文件的内容并将它们分配给变量.我的 json 文件如下所示:

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" } }

在我的本地机器上,我能够使用以下清单加载 json 文件并解析它;它工作得很好.

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']

但是,当我将其移动到 Puppet master 时,这会失败,因为它会在 Puppet master 上查找 json 文件!在我之前的请求 Puppet : How to load file from agent 中,我被告知要使用一个函数,该函数对一个事实很好用,但在这种情况下,我需要根据json 文件的内容.我怎样才能做到这一点?

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 ?

推荐答案

loadjson() 等函数在编译目录的机器上执行.在大多数情况下,这意味着该函数在主服务器上执行.由于 master 上不存在 some_file.json,因此不会加载文件.

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

setcode 块的最后一行作为事实的值返回.在这种情况下,它将公开一个 $::master_hash 事实,该事实将包含来自已解析 json 的哈希值.

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.

这篇关于Puppet:如何从代理加载文件 - 第 2 部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆