Search code examples
rubypuppethostnamefacter

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


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?


Solution

  • 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"