puppet-prod/modules/libs/lib/facter/subnet_facts.rb

39 lines
1.4 KiB
Ruby

# frozen_string_literal: true
require 'ipaddr'
# a class that creates facts based on the subnet
class SubnetAttributes
SUBNET_TO_ATTRIBUTES = {
'198.18.13.0/24' => { environment: 'prod', region: 'syd1', country: 'au' },
'198.18.14.0/24' => { environment: 'prod', region: 'syd1', country: 'au' },
'198.18.15.0/24' => { environment: 'prod', region: 'syd1', country: 'au' },
'198.18.16.0/24' => { environment: 'test', region: 'syd1', country: 'au' },
'198.18.17.0/24' => { environment: 'prod', region: 'drw1', country: 'au' },
'198.18.18.0/24' => { environment: 'test', region: 'drw1', country: 'au' }
}.freeze
# Default attributes if no subnet matches, also defined as a constant
DEFAULT_ATTRIBUTES = { environment: 'unknown', region: 'unknown', country: 'unknown' }.freeze
# provide ip to return attributes
def self.attributes(ip)
SUBNET_TO_ATTRIBUTES.each do |subnet, attrs|
return attrs if IPAddr.new(subnet).include?(IPAddr.new(ip))
end
DEFAULT_ATTRIBUTES
end
end
# Use the primary IP address from facts
ip = Facter.value(:networking)['ip']
# Call the class method directly without creating an instance
subnet_attributes = SubnetAttributes.attributes(ip)
# Add separate facts for environment, region, and country
Facter.add('environment') { setcode { subnet_attributes[:environment] } }
Facter.add('region') { setcode { subnet_attributes[:region] } }
Facter.add('country') { setcode { subnet_attributes[:country] } }