ruby - Chef 模板 - 时间戳

标签 ruby chef-infra

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

例如:

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

显然,这会在每个配方运行时进行评估,并不断更新目标文件,即使其他属性都正常——这是不希望的。

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

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

谢谢,

最佳答案

虽然我同意 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 作为模板来自本地磁盘而不是 Recipe (因为 local true)并用当前时间替换 time 变量.

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

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

关于ruby - Chef 模板 - 时间戳,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28068099/

相关文章:

ruby - 关于ruby中 "gets"的问题

javascript - 如何呈现通过表单提交的 HTML?

vagrant - 带 Knife 的Octohost在裸机上独奏? (UserError:未安装 Vagrant )

nginx - ubuntu 12.04 上的 Chef build-essential Recipe 出错

ruby-on-rails - 如何在Ruby中设置通用错误/异常处理程序回调?

ruby - 在 Mac OSX 上安装 1.9.3 后显示 Ruby 1.8.7

ruby-on-rails - 如何使用 iron_worker 在 iron.io 上要求 '' pg"gem

ruby-on-rails - 分工: Capistrano vs Chef

ruby - 如何打印或调试 Chef 属性

chef-infra - Chef : Uploading modified cookbook not working?