Chef - how to write a custom resource containing DSL for “execute”

↘锁芯ラ 提交于 2019-12-24 03:14:38

问题


I have written a chef definition that posts to our chat server.

Since definitions are not recommended any more, how can I rewrite this as a resource? I'm particularly interested in how to use "event" ways to trigger the code.

File chat\definitions\post.rb :

define :chat_post do

  chat_url = 'https://chat.our.company/hooks/abcdef1234567890'
  message = params[:name]

  execute "echo" do
    command "curl -m 5 -i -X POST -d \"payload={"text": "#{message}"\" #{chat_url}"
    ignore_failure true
  end
end

Calling code in a recipe:

artifacts.each do |artifactItem|
  # deploy stuff
  # ...

  chat_post "#{node['hostname']}: Deployed #{artifact_name}-#{version}"
end

Now, I have read the chef documentation and tried various things (to be precise: a Module, a library and a resource) and read the documentation about chef custom resources, but without success.

Can someone please guide me: how to convert this code to a resource, if that is the proper way to do it (chef 12.6+) ?

I would appreciate to know

  • where in the cookbook does a recipe resource go (chat/recipes, or some place else?)
  • how the code should look (converting from my definition above)
  • how is the new code called (from another recipe) and do I need any includes there

回答1:


From the custom_resource doc something like this should do (untested):

in chat/resources/message.rb:

property :chat_url, String, default: 'https://chat.our.company/hooks/abcdef1234567890'
property :message, String, name_property: true

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

And now in another cookbook:

artifacts.each do |artifactItem|
  # prepare the message:

  chat_message "#{node['hostname']}: Deployed #{artifact_name}-#{version}" do
    action :nothing
  end

  # deploy stuff
  # dummy code follow
  deploy artifactItem['artifact_name'] do
    source "whatever_url/#{artifactItem}
    notifies :send,"chat_message[#{node['hostname']}: Deployed #{artifactItem["artifact_name"]}-#{artifactItem['artifact_name']}]"
  end
end

By default notifications are delayed, so the chat_message resource will fire only at end of run.

you deploy cookbook will have to depends on the chat cookbook to be able to call its custom_resource.



来源:https://stackoverflow.com/questions/39488843/chef-how-to-write-a-custom-resource-containing-dsl-for-execute

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!