厨师食谱 FileEdit insert_line_after_match 和 insert_line_if_no_match

chef recipe FileEdit insert_line_after_match and insert_line_if_no_match

我想使用厨师食谱食谱编辑文件。 该文件现在显示为,

[attribute1]
foo=bar
[attribute2]
....

我想改成这样:

[attribute1]
foo=bar
newfoo=newbar
[attribute2]
....

所以基本上,我想添加一行,如果它不存在于文件中,我想在该文件中的特定行之后添加它。

我在 Class: Chef::Util::FileEdit 下找到了 2 个选项,它们在这里可能有用 insert_line_after_matchinsert_line_if_no_match。但我想要一个可以执行这两个操作的选项。如果我使用 insert_line_after_match,它适用于第一个 运行 但对于下一个 运行 它只是继续添加行,即使行已经在文件中。如果文件中不存在行,insert_line_if_no_match 在文件末尾添加行,但我想在该文件中的特定行之后添加行。

我对厨师食谱有点陌生。有什么办法可以解决以上问题吗?

请不要使用 FileEdit。它是 API 的内部 而不是 供 public 使用。您想要的是 line 食谱,特别是 replace_or_add 自定义资源。确保非常仔细地制作正则表达式。

一般我们不推荐这种管理方式,因为它非常脆弱,很容易被不相关的变更破坏。更好的选择是使用 template 资源或类似资源以聚合方式管理整个文件。

我建议不要编辑文件,而是覆盖它们。您应该在食谱中创建一个模板或文件,然后使用 templatecookbook_file 资源用食谱中的文件覆盖机器上的文件。

您的配置文件看起来类似于 toml, so you can also use toml-rb gem 从 json(数据包)或类似的属性生成此文件:

chef_gem 'toml-rb' do
  compile_time false
end

file '/path/to/file.conf' do
  content( lazy do
    require 'toml'
    "# This file is managed by Chef\n" +
    TOML.dump( my_json )
  end )
end