chef: how to get a timestamp at *convergence* rather than *compile* time

2.2k Views Asked by At

Please consider this code at the end of my deploy_to_tomcat recipe:

  unless Chef::Config[:solo]
    chat_message "Deployed #{artifact_name} `#{Time.new.strftime("%Y-%m-%d %H:%M")}`"
  end

It posts a message to chat: Deployed my-web-app 2016-11-03 12:31

However, I notice the timestamp from Time.new is a little out - it seems to be the timestamp when the recipe was compiled, rather than when the resources coverged and ran, a couple of minutes later.

So I tried this, but it didn't work (timeNow was still undefined when message was posted to chat)

  timeNow = "undefined"
  ruby_block "set-time-now" do
    block do
      timeNow = Time.new.strftime("%Y-%m-%d %H:%M:%S")
    end
  end

  unless Chef::Config[:solo]
    chat_message "Deployed #{artifact_name} `#{timeNow}`"
  end

Is there an easier way to get my timestamp to reflect the actual time (rather than when the recipe started) ?

2

There are 2 best solutions below

1
On BEST ANSWER

Not sure what you try to solve, but you can use node to store timestamp.

node.normal[:cookbook_name][:deployment_time] = "undefined"
ruby_block "set-time-now" do
  block do
    node.normal[:cookbook_name][:deployment_time] = Time.new.strftime("%Y-%m-%d %H:%M:%S")
  end
end

unless Chef::Config[:solo]
  chat_message "Deployed #{artifact_name} #{node[:cookbook_name][:deployment_time]}"
end
0
On

What you want is a lazy evaluator like this (give or take that I don't know how your chat_message resource is written):

unless Chef::Config[:solo]
  chat_message "deployed" do
    message lazy { "Deployed #{artifact_name} `#{Time.new.strftime("%Y-%m-%d %H:%M")}`" }
  end
end

That will delay evaluation of the message string until converge time.