有条件地执行资源

时间:2015-03-08 18:16:03

标签: chef conditional-statements chain

我在菜单中定义了以下2个资源来发出HTTP请求。我基本上需要根据action 2的结果检查条件来执行action 1。如果来自action 1的条件不匹配,我需要让食谱睡一段时间,然后再次尝试action 1

最好的方法/方法是什么?

webhooks_request "Action 1" do
   uri "example.net/data1"
   post_data ({ 'value1' => '1', 'value2' => '2'})
   expected_response_codes [ 200, 201 ]
   action :post
end

我正在使用以下ruby_block来处理action 1的结果,所以我认为应该可以根据匹配条件执行action 2

ruby_block "Parse Response" do
   #Parse the result from action 1
end

webhooks_request "Action 2" do
   uri "example.net/data2"
   post_data ({ 'value1' => '1', 'value2' => '2'})
   expected_response_codes [ 200, 201 ]
   action :post
end

1 个答案:

答案 0 :(得分:2)

我会做什么(警告:这是未经测试的代码):

node.runstate['my_hook']['retries']=10

webhooks_request "Action 1" do
   uri "example.net/data1"
   post_data ({ 'value1' => '1', 'value2' => '2'})
   expected_response_codes [ 200, 201 ]
   action :post
   notifies :run, "ruby_block[Parse Response]", :immediately 
end

ruby_block "Parse Response" do
   action :nothing
   block do
     #Parse the result from action 1
     if "result ok from action 1"
       self.notifies :post,"webhooks_request[Action 2]",:immediately
     else
       node.runstate['my_hook']['retries'] -= 1 # decrease to avoid infinite loop
       sleep(10)
       self.notifies :post,"webhooks_request['Action 1']",:immediately
     end
   end
end

webhooks_request "Action 2" do
   uri "example.net/data2"
   post_data ({ 'value1' => '1', 'value2' => '2'})
   expected_response_codes [ 200, 201 ]
   action :nothing
end

另一种方法是做"行动1"调用ruby块内部直接解析它的输出。

沿线的某些东西可以做(仍然是未经测试的代码):

ruby_block "try webhook" do
  block do
    r = Chef::Resource::WebhooksRequest.new('Action 1',run_context)
    r.uri "example.net/data2"
    r.post_data ({ 'value1' => '1', 'value2' => '2'})
    r.expected_response_codes [ 200, 201 ]
    hookretries=10 
    while hookretries do
      r.run_action :post
      # parse data from Action 1
      if "action 1 returned NOK"
         hookretries -= 1
      else 
         break
      end
    end
    hook_retries > 0 # to trigger notify if we're not in timeout
  end
  notifies :post, "webhooks_request[Action 2]", :immediately
end
webhooks_request "Action 2" do
   uri "example.net/data2"
   post_data ({ 'value1' => '1', 'value2' => '2'})
   expected_response_codes [ 200, 201 ]
   action :nothing
end