Merge pull request 'feat: merge subnet facts' (#133) from neoloc/env_fact into develop

Reviewed-on: unkinben/puppet-prod#133
This commit is contained in:
Ben Vincent 2024-03-10 14:13:46 +09:30
commit df05be21f6
3 changed files with 34 additions and 56 deletions

View File

@ -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

View File

@ -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

View File

@ -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] } }