Skip to content

Instantly share code, notes, and snippets.

@bschonec
Created March 7, 2025 17:49
Show Gist options
  • Select an option

  • Save bschonec/3da5ebb3e965df5d5c18a82f337e22aa to your computer and use it in GitHub Desktop.

Select an option

Save bschonec/3da5ebb3e965df5d5c18a82f337e22aa to your computer and use it in GitHub Desktop.
Spec Test
# frozen_string_literal: true
require 'spec_helper'
require 'facter'
require 'facter/application'
describe 'test Oracle region fact' do
# subject { Facter.fact(:region) }
ips = {
'10.105.64.1' => { 'region' => 'chicago' },
'10.105.128.1' => { 'region' => 'ashburn' },
'10.105.222.1' => { 'region' => 'oracle' },
'1.2.3.4' => { 'region' => 'other' },
}
context 'checking regions locations' do
ips.each do |ip, region|
context "checking region #{region}" do
before(:each) do
# perform any action that should be run before every test
Facter.clear
allow(Facter.fact(:networking)).to receive(:value).and_return(ip)
end
it "uses the built-in facts #{ip} to return the application hash for #{region['region']}" do
expect(Facter.fact(:region).value).to eq('chicago')
end
end
end
end
@bschonec
Copy link
Author

bschonec commented Mar 7, 2025

require 'ipaddr'

Facter.add('region') do
  confine kernel: 'Linux'

  setcode do
    networks = { '10.105.64.0/19'  => { 'name' => 'chicago' },
                 '10.105.128.0/17' => { 'name' => 'ashburn' },
                 '10.105.0.0/16' => { 'name' => 'oracle' },
                 '0.0.0.0/0' => { 'name' => 'other' } }

    region = ''
    my_ip = Facter.value('networking')['ip']

    # loop over the networks hash and see if the IP we're looking for
    # is defined in the hash.
    networks.each do |key, value|
      # Get the subnet that we're checking from the key name.
      # https://stackoverflow.com/questions/3518365/find-out-if-an-ip-is-within-a-range-of-ips#3519831
      if IPAddr.new(key).include? my_ip
        region = value['name']
        break
      end
    end
    region
  end
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment