diff --git a/modules/libs/lib/facter/country.rb b/modules/libs/lib/facter/country.rb deleted file mode 100644 index 52977d6..0000000 --- a/modules/libs/lib/facter/country.rb +++ /dev/null @@ -1,28 +0,0 @@ -# frozen_string_literal: true - -# set country based on the subnet - -Facter.add('country') do - setcode do - # use facts['networking']['ip']to find the promary IP address - ip = Facter.value(:networking)['ip'] - - # subnet to region mapping - subnet_to_country = { - '198.18.17.0/24' => 'au' - } - - require 'ipaddr' - - # Find the region for the IP - country = 'stateless' # default to 'stateless' if no country matches - subnet_to_country.each do |subnet, country_initial| - if IPAddr.new(subnet).include?(IPAddr.new(ip)) - country = country_initial - break - end - end - - country - end -end diff --git a/modules/libs/lib/facter/region.rb b/modules/libs/lib/facter/region.rb deleted file mode 100644 index 248fb12..0000000 --- a/modules/libs/lib/facter/region.rb +++ /dev/null @@ -1,28 +0,0 @@ -# frozen_string_literal: true - -# set region based on the subnet - -Facter.add('region') do - setcode do - # use facts['networking']['ip']to find the promary IP address - ip = Facter.value(:networking)['ip'] - - # subnet to region mapping - subnet_to_region = { - '198.18.17.0/24' => 'drw1' - } - - require 'ipaddr' - - # Find the region for the IP - region = 'lost' # default to 'lost' if no region matches - subnet_to_region.each do |subnet, region_name| - if IPAddr.new(subnet).include?(IPAddr.new(ip)) - region = region_name - break - end - end - - region - end -end diff --git a/modules/libs/lib/facter/subnet_facts.rb b/modules/libs/lib/facter/subnet_facts.rb new file mode 100644 index 0000000..7e26ee9 --- /dev/null +++ b/modules/libs/lib/facter/subnet_facts.rb @@ -0,0 +1,34 @@ +# frozen_string_literal: true + +require 'ipaddr' + +# a class that creates facts based on the subnet +class SubnetAttributes + SUBNET_TO_ATTRIBUTES = { + '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] } }