在 Chef 中读取文件而不写入节点

Read files in Chef without writing to the node

我正在尝试读取文件内容并在我的 ruby 代码中使用它。在此步骤中,我不会尝试在引导节点上执行任何操作。我想要做的就是读取一个 JSON 文件,该文件将驻留在 cookbook 的文件夹中,然后读取文件的内容并执行一些操作。我只想在我的代码本身中使用来自 JSON 的值。代码示例如下所示。感谢任何帮助。

属性:default.rb

default["xyz"]["ohs_servers"]=[
  {"hostname"=> "intf301.linux.xyz.com","name" => "INTFIN_OHS_001", "short_name" => "OGS", "port" => "9931"},
  {"hostname"=> "intf302.linux.xyz.com","name" => "INTFIN_OHS_001", "short_name" => "OHS", "port" => "9931"}
]

机器:machines.rb

require 'rubygems'
require 'json'
require 'pp'

json = File.read('environment.json')
obj = JSON.parse(json)

number = obj["name"]

x = node["xyz"]["ohs_servers"][number]["hostname"]

JSON 食谱文件夹中的文件:environment.json

{
  "template_name": "environment_template",
  "number": 0
}

即使我真的不明白为什么你不想为此使用属性:

你想要的是即使没有资源调用它们也能确保 cookbook 文件在缓存中,方法是在具有 no_lazy_load 属性的节点上配置 client.rbtrue

引用 documentation 关于这个选项:

no_lazy_load Use to download all cookbook files and templates at the beginning of the chef-client run. Default value: true.

我不确定默认值是否随 12 或哪个版本发生了变化,但我很确定它在 chef 11 中是错误的(调用引用它们的提供程序时加载文件或模板)

然后您可以使用

读取您的文件
File::read("#{Chef::Config['file_cache_path']}/cookbooks/my_cookbook/files/my_file.json")

编辑:刚看到 Stephen King 的评论,我或多或少转述了 Seth Vargo 的回答:/

使用cookbook_file然后添加run_action(:create)

cookbook_file "myfile.txt" do
   path "somepathyouwantthefilebe/myfile.txt"
   source "myfile.txt"  #the name of the file in files folder of your cookbook"
end.run_action(:create)  # read notes** bellow

然后你可以从中读取一些 ruby 代码 例如

File::read("somepathyouwantthefilebe/myfile.txt")

** 运行 操作是必需的,因为您在 chef-zero

中组合了 ruby 代码和资源