问题描述
我正在寻找一个基于主机名前缀的角色,但遇到了一些问题. Ruby对我来说是新手,尽管我已经进行了广泛的寻找解决方案的工作,但我仍然感到困惑.
I'm looking to create a role based on host name prefix and I'm running into some problems. Ruby is new to me and although I've done extensive searching for a solution, I'm still confused.
主机名看起来像这样:
- work-server-01
- home-server-01
这是我写的:
require 'facter'
Facter.add('host_role') do
setcode do
hostname_array = Facter.value(:hostname).split('-')
first_in_array = hostname_array.first
first_in_array.each do |x|
if x =~ /^(home|work)/
role = '"#{x}" server'
end
role
end
end
我想在角色分配中使用变量插值,但是我想将case语句和'when'一起使用是不正确的.请记住,我是Ruby的新手.
I'd like to use variable interpolation within my role assignment, but I feel like using a case statement along with 'when' is incorrect. Please keep in mind that I'm new to Ruby.
有人会对我如何实现目标有任何想法吗?
Would anybody have any ideas on how I might achieve my goal?
推荐答案
模式匹配主机名事实
以下是代码的相对DRY重构:
Pattern-Matching the Hostname Fact
The following is a relatively DRY refactoring of your code:
require 'facter'
Facter.add :host_role do
setcode do
location = case Facter.value(:hostname)
when /home/ then $&
when /work/ then $&
else 'unknown'
end
'%s server' % location
end
end
通常,它只查找正则表达式匹配项,并将匹配项的值分配给 location ,然后将其作为格式化字符串的一部分返回.
Mostly, it just looks for a regex match, and assigns the value of the match to location which is then returned as part of a formatted string.
在我的系统上,主机名与"home"或"work"都不匹配,所以我正确地得到了:
On my system the hostname doesn't match either "home" or "work", so I correctly get:
Facter.value :host_role
#=> "unknown server"
这篇关于如何从主机名创建自定义:host_role事实?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!