Search code examples
rubychef-infracookbookrecipe

Ruby / Chef: is there a way to refer to the resource 'name' and pass to a function?


Please see the following code, using the log resource in chef.

log 'Hello there' do
  level :info
  notifies :run, "log_to_chat('Hello there')"
end

Is there a way to refer to the resource name (in this case: 'Hello there') when I pass it to the function log_to_chat.

I imagine something like:

log 'Hello there' do
  level :info
  notifies :run, "log_to_chat(#{name})"
end

Adding my attempts for log_to_chat.

Attempt 1:

resource_name :log_to_chat

property :message, kind_of: String, name_property: true

chat_url = 'https://chat.server/abcdef'

action :run do
  execute do
    command "curl -m 5 -i -X POST -d \"payload={...}\" #{chat_url}"
    ignore_failure true
  end
end

Question: how to pass the :message parameter as a one liner from the notifies line?

notifies :run, "log_to_chat[message]", --pass :message how??--

Attempt 2:

module Chat
  def log_to_chat(message)
    chat_url = 'https://chat.server/abcdef'
    action :run do
      execute "curl" do
        command "curl -m 5 -i -X POST -d \"payload={...}\" #{chat_url}"
        ignore_failure true
      end
    end
  end
end

edit: attempt 2 didn't work since you can't use resources in a definition


Solution

  • You can refer to the name variable. From documentation you can read that "name is the name of the resource block". Keep in mind that you want to use the name of block (which is Hello there in your case) instead of resource name (which is log in the snippet from question)