【问题标题】:Multiple File Replace in Ruby Chef RecipeRuby Chef 食谱中的多个文件替换
【发布时间】:2017-09-13 02:34:29
【问题描述】:

这里的厨师新手,对 Ruby 也有一点了解。

我不确定为什么我不能在我正在处理的示例配方中的文件中写入两次。

我的配置文件中有两个模式需要替换,但这样做 不更新两种模式;只有一个更新,另一个没有更新。

ruby_block " Update Config File " do
  block do
    file_name = config_file
    text = File.read(file_name)
    File.write(file_name, text.gsub(search_value, replace_value))
    File.write(file_name, text.gsub(second_search_value, second_replace_value))
  end
  only_if { File.exists?("#{config_file}") }
end

我知道我可以做另一个 ruby​​_block 但我只是想知道我缺少什么来完成这项工作。我只想要一个 ruby​​_block 而不是两个,因为我正在编辑同一个文件。

【问题讨论】:

    标签: ruby chef-infra


    【解决方案1】:

    让我们逐行看:

    1. text = File.read(file_name)

    很简单,我们将文件内容**读*到text

    1. File.write(file_name, text.gsub(search_value, replace_value))

    我们在原来的text中做一个globalsubstitution并将其写入文件

    1. File.write(file_name, text.gsub(second_search_value, second_replace_value))

    我们在原来的text中做了一个globalsubstitution并将其写入文件

    当然,当您写入 3 时,您会覆盖 2. 中的更改。

    一种可能的方法是 gsub 两次,最后只写一次,但真的不要那样做,做这种更改很脆弱,随时可能中断,或者在每次运行时插入更改并破坏你的配置。
    让厨师用template 管理整个文件,

    【讨论】:

    • 只是为了呼应底部部分,使用模板资源确实更好,因为它是一种更收敛的方法。正如您的示例所示,如果您的正则表达式没有仔细编写,您将面临意外替换的风险。
    猜你喜欢
    • 2014-11-06
    • 1970-01-01
    • 2015-09-17
    • 1970-01-01
    • 2017-10-25
    • 1970-01-01
    • 2015-10-24
    • 2014-05-08
    • 1970-01-01
    相关资源
    最近更新 更多