vikingsteve vikingsteve - 16 days ago 5
Ruby Question

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

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) ?

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
Comments