How can I create a custom :host_role fact from the hostname?

ぃ、小莉子 提交于 2020-05-31 04:08:08

问题


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.

Host names look like this:

  • work-server-01
  • home-server-01

Here's what I've written:

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

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?


回答1:


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

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.

On my system the hostname doesn't match either "home" or "work", so I correctly get:

Facter.value :host_role
#=> "unknown server"


来源:https://stackoverflow.com/questions/25654478/how-can-i-create-a-custom-host-role-fact-from-the-hostname

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!