diff --git a/lib/puppet/functions/extlib/netmask_to_cidr.rb b/lib/puppet/functions/extlib/netmask_to_cidr.rb new file mode 100644 index 0000000..13f4990 --- /dev/null +++ b/lib/puppet/functions/extlib/netmask_to_cidr.rb @@ -0,0 +1,18 @@ +# @summary Converts an octet netmask address of the form 255.255.255.0 into its CIDR variant. +# Thus making it directly usable with the values from facter. +# +Puppet::Functions.create_function(:'extlib::netmask_to_cidr') do + # @param netmask IPv6 or IPv4 netmask in octet notation + # @return CIDR / prefix length + # @example calling the function + # extlib::netmask_to_cidr('255.0.0.0') + dispatch :netmask_to_cidr do + param 'Stdlib::IP::Address::Nosubnet', :netmask + return_type 'Integer[0, 128]' + end + + def netmask_to_cidr(netmask) + dummy_addr = IPAddr.new(netmask).ipv6? ? '::' : '0.0.0.0' + IPAddr.new("#{dummy_addr}/#{netmask}").prefix + end +end diff --git a/spec/functions/extlib/netmask_to_cidr.rb b/spec/functions/extlib/netmask_to_cidr.rb new file mode 100644 index 0000000..5b0c02e --- /dev/null +++ b/spec/functions/extlib/netmask_to_cidr.rb @@ -0,0 +1,35 @@ +require 'spec_helper' + +describe 'extlib::netmask_to_cidr' do + it 'exists' do + is_expected.not_to be_nil + end + + context 'when called with no parameters' do + it { is_expected.to run.with_params.and_raise_error(ArgumentError) } + end + + context 'when called with a Integer' do + it { is_expected.to run.with_params(42).and_raise_error(ArgumentError) } + end + + context 'when called with a String thats not an ip address' do + it { is_expected.to run.with_params('42').and_raise_error(ArgumentError) } + end + + context 'when called with an IP Address that is not in the pure octet notation' do + it { is_expected.to run.with_params('127.0.0.1/8').and_raise_error(ArgumentError) } + end + + context 'when called with an IP Address that is not in the pure octet notation' do + it { is_expected.to run.with_params('fe80::800:27ff:fe00:0').and_raise_error(ArgumentError) } + end + + context 'when called with an IPv4 octet netmask' do + it { is_expected.to run.with_params('255.0.0.0').and_return(8) } + end + + context 'when called with an IPv6 octet netmask' do + it { is_expected.to run.with_params('ffff:ffff::').and_return(32) } + end +end