【问题标题】:Can I use guards to chef if a windows service is running?如果 Windows 服务正在运行,我可以使用警卫来做饭吗?
【发布时间】:2019-07-15 20:21:28
【问题描述】:

我正在编写厨师食谱,并且仅在服务不工作时才需要执行操作(运行批处理)。 我用这个sn-p:

batch 'run commnad' do
  cwd target_path + '/bin/win64'
    code 'command to be executed'
    not_if '::Win32::Service.exists?("Service name")'
end

但它似乎不起作用。在看到this 问题后,我使用 if 子句而不是守卫更改了流程,它工作正常:

if !::Win32::Service.exists?("Service name") then
  batch 'Install zabbix agent' do
    cwd target_path + '/bin/win64'
    code 'command to be executed'
  end
end

但据我了解,这不应该是管理这个问题的正确方法,所以我想知道:为什么警卫不能正常工作?

谢谢, 米歇尔。

【问题讨论】:

    标签: ruby chef-infra chef-recipe


    【解决方案1】:

    您编写not_if 语句的方式将命令作为shell 脚本运行。 shell 不知道 Ruby 代码,因此整个命令将失败。 需要先:

    require win32/service

    为了在 Ruby 代码中使用 not_if,您应该将它放在一个块中:

    not_if { ::Win32::Service.exists?("Service name") }
    

    在此处查看更多示例(在页面上搜索not_if):
    https://docs.chef.io/resource_common.html

    【讨论】:

    • {} 解决了这个问题。我没想到。谢谢!
    • 如果你想做更多的Ruby-ish,你也可以在批处理资源调用中附加一个条件,即batch 'run command' do ... end unless <logic for disabled service>
    【解决方案2】:

    这是工作示例(Chef 13)

       require 'win32/service'
       windows_service "jenkins" do
          action [:stop, :disable]
          only_if { ::Win32::Service.exists?("jenkins")}
       end
    

    【讨论】:

      猜你喜欢
      • 2011-07-14
      • 2023-03-17
      • 2018-11-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多