Skip to content

Instantly share code, notes, and snippets.

@acidprime
Last active August 22, 2017 19:23
Show Gist options
  • Save acidprime/85b84d8c84ca520a3521 to your computer and use it in GitHub Desktop.
Save acidprime/85b84d8c84ca520a3521 to your computer and use it in GitHub Desktop.
Simple CIDR matching with a fact
require 'ipaddr'
# Accessible in puppet as $::subnet
Facter.add(:subnet) do
setcode do
# Mapping of vlans to ipaddresses
# NOTE: To extend this fact, modify this hash
vlan_segments = {
'prod' => IPAddr.new('10.10.10/22'),
'dev' => IPAddr.new('11.11.11/22'),
'uat' => IPAddr.new('12.12.12/22'),
'cloud' => IPAddr.new('13.13.13/24')
}
segment_name = nil
# Iterate through all segments and find the one that matches
vlan_segments.each do |segment, address|
if address.include?(Facter.value(:ipaddress))
segment_name = segment
end
end
# Return the name of the segment that matches
segment_name
end
end
@natemccurdy
Copy link

Here's a version that lets you have multiple ranges per vlan/datacenter....

require 'ipaddr'
# Accessible in puppet as $::datacenter
Facter.add(:datacenter) do
  setcode do
    # Mapping of vlans to IP addresses
    # NOTE: To extend this fact, modify this hash
    vlan_segments = {
      'prod'  => IPAddr.new('10.10.10.0/22'),
      'dev'   => IPAddr.new('11.11.11.0/22'),
      'uat'   => IPAddr.new('12.12.12.0/22'),
      'cloud' => [
        IPAddr.new('13.13.13.0/24'),
        IPAddr.new('192.168.0.0/24')
      ]
    }

    segment_name = nil

    # Iterate through all segments and find the one that matches
    vlan_segments.each do |segment, subnets|
      Array(subnets).each do |address|
        segment_name = segment if address.include?(Facter.value(:ipaddress))
      end
    end

    # Return the name of the segment that matches
    segment_name
  end
end

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