2015-03-08 107 views
1

我在烹飪書中定義了以下兩個資源,它們發出HTTP請求。我基本上需要根據action 1的結果檢查條件執行action 2。如果來自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 

回答

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_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 
+0

非常感謝 - 我要試試這個\ – user1513388 2015-03-09 22:05:12

+0

我想補充,如果你想跳過#2如果第1超時,然後把'not_if {node.runstate ['my_hook'] ['retries'] <0}'(你可能必須把它包裝在一個懶惰的塊中。 – 2015-03-10 05:27:02

+0

@TejayCardon我可能是錯的沒有測試過),但是我的最後一行代碼塊會返回true或false,而且如果ruby_block返回false,那麼IIRC(但確實不確定)通知不應該被激怒(我必須測試這個來確認這種行爲) – Tensibai 2015-03-10 09:29:18