1
votes

While implementing a templated config file using chef 11.x I'd like to insert the current date/time into the file whenever it is updated.

For example:

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

Obviously this evaluates on each recipe run and constantly updates the target file even when the other attributes are OK - which is not desired.

Therefore is anyone aware of a solution? I'm not aware of any built-in logic within Chef to achieve this and I don't know of a built-in chef variable that I could evaluate within a ruby block that would only be true if the other attributes are out of compliance (as that would provide a potential workaround).

I know that I could run an execute type operation which only gets run after the template resource has been fired, and it expands a variable in the file to achieve this, but I don't like the concept or idea of doing that.

Thanks,

2

2 Answers

4
votes

While I agree with Tensibai that what you expect is not what Chef is made for.

What I want to add (because some time ago I searched pretty long for that) is how to include the current time stamp in a file, once it was modified through Chef (somehow you have to circumvent that it always updates the time stamp).

The result can be found here, simplified, untested version:

  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

Everytime, when the content of /tmp/example.txt.erb changes, it triggers /tmp/example.txt to be written - taking /tmp/example.txt.erb as template from the local disk instead of from the cookbook (because local true) and replacing the time variable with the current time.

So the only variable that has to be replaced when writing /tmp/example.txt is the time, thus the example.txt.erb template looks like this:

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

That's the way chef works, it makes a diff between rendered template and actual file, as the timestamp is not the same it replace it.

Your alternate solution won't work either for the same reason, a placeholder will be different than the datetime of the replacements.

The best you can do is write a file aside named 'myfile-last-update' for exemple with a text inside describing the last update of it.

But last question: Why would you want to have the time inside the file as it's already present in the file attribute (ls -l should give you this information) ?