厨师(Chef) - 在其他资源失败时运行资源

5

我有两个名为command_1command_2execute资源。

如果command_1执行失败,我想要运行command_2,然后再次运行command_1

就像这样:

execute 'command_1' do
  command "ipa host-del #{machine_name}"
  action :run
  ignore_failure true
  on_failure { notifies :run, 'execute['command_2']', :immediately }
end

execute 'command_2' do
  command "ipa host-mod --certificate  #{machine_name}"
  action :nothing
  notifies :run, 'execute['command_1']', :immediately
end

我该如何用实际有效的替代on_failure(如果Chef有这个功能将会很棒)?

1
我看不到直接的方法。你能否用 not_if/only_if 块来保护第二个资源,以防止它在第一个资源成功时运行?也就是说,当 host-del 失败时,我希望类似于 ipa host-list #{machine_name} 的东西包含主机。在 not_if { mixlib shellout blabla contains #{machine_name} 中检查这个。 - StephenKing
我假设command_1有一个保护措施,以免在每次chef运行时被执行,因此我认为你最好直接在ruby_block中使用shell_out,并在该块中实现逻辑。 - Tensibai
1个回答

3

您最好先执行command_2命令,然后通过检查是否需要运行来保护它。我不确定该命令的作用是什么,但如果可以以某种方式验证其是否需要,则可以这样做。

如果无法验证是否需要执行command_2命令,则可以尝试使用以下方法:

execute 'command_1' do
  command "ipa host-del #{machine_name} && touch /tmp/successful"
  action :run
  ignore_failure true
end

execute 'command_2' do
  command "ipa host-mod --certificate  #{machine_name}"
  action :run
  notifies :run, 'execute['command_1']', :immediately
  not_if { ::File.exist? '/tmp/successful' }
end

file '/tmp/successful' do
  action :delete
end

这将运行 command_1 命令,如果成功则会执行touch /tmp/successful。然后运行 command_2 命令,但仅当 /tmp/successful 不存在时才运行。如果命令 command_2 运行,则立即通知命令 command_1 再次运行。为了清理下一次运行,我们添加file资源来确保删除/tmp/successful


好的。代码没有显示为代码块,你能修复一下吗? - JahMyst
没问题@JahMyst。不太确定之前发生了什么,因为我确实在之前有正确的格式。算了。 - Tejay Cardon
阅读更多后,我想补充一点,更好的做法是在“execute”资源内使用creates '/tmp/successful'来创建临时文件。如此以来,“creates”将成为“execute”资源的一个属性,具体可参考以下链接:https://docs.chef.io/resource_execute.html - JahMyst
@OlivierCervello的creates实际上并不会创建文件。它只是not_if { ::File.exist?(<file path>) }的快捷方式。你可以在execute 'command_2'上使用它,但你的意图会变得不太清晰,因为command_2并没有任何预期要创建那个文件。 - Tejay Cardon
你说得对,我完全错了。不过这有点误导人。 - JahMyst

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接