Chef 模板 - 时间戳

Chef Template - Timestamping

在使用 chef 11.x 实现模板化配置文件时,我想在更新时将当前 date/time 插入到文件中。

例如:

# Created By : core::time-settings
# On         : <%= Time.now %>

显然这会评估每个配方 运行 并不断更新目标文件,即使其他属性都正常 - 这是不需要的。

因此有人知道解决方案吗?我不知道 Chef 中有任何内置逻辑可以实现这一点,我也不知道我可以在 ruby 块中评估的内置 chef 变量只有在其他属性时才为真不合规(因为这将提供潜在的解决方法)。

我知道我可以 运行 一个执行类型的操作,它只在模板资源被触发后得到 运行,它扩展文件中的一个变量来实现这个,但我不知道不喜欢这样做的概念或想法。

谢谢,

这就是 chef 的工作方式,它在呈现的模板和实际文件之间产生差异,因为时间戳不相同,它会替换它。

出于同样的原因,您的替代解决方案也不起作用,占位符将与替换的日期时间不同。

你能做的最好的事情就是在旁边写一个名为 'myfile-last-update' 的文件,例如,里面有一段描述它的最后更新的文本。

但最后一个问题:你为什么要在文件中包含时间,因为它已经存在于文件属性中(ls -l 应该给你这个信息)?

虽然我同意 Tensibai 您所期望的不是 Chef 的用途。

我想添加的(因为前段时间我搜索了很长时间)是如何在文件中包含当前时间戳,一旦它被 Chef 修改(你必须以某种方式避免它总是更新时间戳)。

可以查到结果here,简化版,未经测试的版本:

  time =  Time.new.strftime("%Y%m%d%H%M%S")

  template "/tmp/example.txt" do
    source    "/tmp/example.txt.erb" # the source is not in a cookbook, but on the disk of the node!
    local     true
    variables(
      :time => time
    )
    action :nothing
  end

  template "/tmp/example.txt.erb" do
    variables(
      variable1 => "test"
     )
    notifies :create, resources(:template => "/tmp/example.txt"), :immediately
  end

每次,当 /tmp/example.txt.erb 的内容发生变化时,它会触发写入 /tmp/example.txt - 将 /tmp/example.txt.erb 作为本地磁盘而不是食谱的模板(因为 local true) 并将 time 变量替换为当前时间。

所以在写 /tmp/example.txt 时唯一需要替换的变量是时间,因此 example.txt.erb 模板如下所示:

# my template
time: <%%= @time %>
other stuff here.. <%= @variable1 %>