我在菜单中定义了以下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
答案 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