简体   繁体   English

在Ruby中使用RegEx的if语句(首席配方)

[英]If statement using RegEx in Ruby (Chef recipe)

I have a Chef recipe in which I'm trying to say: 我有一个厨师食谱,我想在其中说:

"If the server's hostname ends in -1, then enable and start the newrelic-sysmond and newrelic-daemon services, else, disable those services" “如果服务器的主机名以-1结尾,则启用并启动newrelic-sysmond和newrelic-daemon服务,否则,禁用这些服务”

using RegEx to determine whether the hostname does end in -1 or not. 使用RegEx确定主机名是否以-1结尾。

Using my attempt below, the services seem to enable and start regardless of whether the hostname ends in -1 or not. 通过下面的尝试,无论主机名是否以-1结尾,这些服务似乎都可以启用和启动。 I'm quite new to Ruby and Chef so I wouldn't be surprise if my code is incorrect: 我是Ruby和Chef的新手,所以如果我的代码不正确,也不会感到惊讶:

if node["hostname"] =~ /^.*-1$/
    service 'newrelic-sysmond' do
        action [ :enable, :start ]
    end
    service 'newrelic-daemon' do
        action [ :enable, :start ]
    end
else
    service 'newrelic-sysmond' do
        action [ :disable ]
    end
    service 'newrelic-daemon' do
        action [ :disable ]
    end
end

There is a chance that the hostname isn't what you think it is. 主机名可能与您认为的不一样。 You probably want something like if node['machinename'] =~ /-1$/ or if node['machinename'].end_with?('-1') . 您可能想要if node['machinename'] =~ /-1$/if node['machinename'].end_with?('-1') Otherwise that looks okay. 否则看起来还可以。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM