资源的条件执行

Conditional execution of resources

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

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

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

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

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

另一种方法是在 ruby 块内执行 "Action 1" 调用以直接解析它的输出。

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

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