inet6 prefix utility

Utility to handle prefixing IPv6 address with `inet6:`.

This is useful for services relying on python-memcached
which require the inet6:[<ip_address]:<port> format.

Change-Id: Ibd280929f62bae61f34b2984af7710fbd422264b
This commit is contained in:
Harald Jensås 2019-05-24 01:23:53 +02:00
parent 6399a0e3f6
commit 1f13d87fdf
3 changed files with 55 additions and 0 deletions

View File

@ -0,0 +1,31 @@
# Add inet6 prefix if the argument is an IPv6 address.
#
# This is useful for services relying on python-memcached which require
# the inet6:[<ip_address]:<port> format.
#
# Returns the argument untouched otherwise.
Puppet::Functions.create_function(:inet6_prefix) do
def inet6_prefix(*args)
require 'ipaddr'
result = []
args = args[0] if args[0].kind_of?(Array)
args = [args] unless args.kind_of?(Array)
args.each do |ip|
begin
unless ip.match(/^inet6:.+/)
ip_parts = ip.split(/\s|\[|\]/).reject { |c| c.empty? }
if IPAddr.new(ip_parts[0]).ipv6?
Puppet.debug("#{ip} is changed to inet6:[#{ip}]")
ip = "inet6:[#{ip_parts.shift}]#{ip_parts.join}"
end
end
rescue IPAddr::AddressFamilyError, IPAddr::Error, IPAddr::InvalidAddressError, IPAddr::InvalidPrefixError, ArgumentError, NoMethodError => e
# ignore it
end
result << ip
end
return result[0] if args.size == 1
result
end
end

View File

@ -0,0 +1,6 @@
---
features:
- |
Utility to handle prefixing IPv6 address with ``inet6:``. This is useful
for services relying on python-memcached which require the
``inet6:[<ip_address]:<port>`` format.

View File

@ -0,0 +1,18 @@
require 'spec_helper'
describe 'inet6_prefix' do
it { should run.with_params(false).and_return(false)}
it { should run.with_params('not_an_ip').and_return('not_an_ip')}
it { should run.with_params('127.0.0.1').and_return('127.0.0.1')}
it { should run.with_params('::1').and_return('inet6:[::1]')}
it { should run.with_params('[::1]:80').and_return('inet6:[::1]:80')}
it { should run.with_params('[2001::01]').and_return('inet6:[2001::01]')}
it { should run.with_params('[2001::01]:80').and_return('inet6:[2001::01]:80')}
# You're not forced to pass an array, a list of argument will do.
it { should run.with_params('::1','::2').and_return(['inet6:[::1]','inet6:[::2]'])}
it { should run.with_params(['::1','::2']).and_return(['inet6:[::1]','inet6:[::2]'])}
it { should run.with_params(['::1','[::2]','::3']).and_return(['inet6:[::1]','inet6:[::2]','inet6:[::3]'])}
it { should run.with_params(['192.168.0.1','[::2]']).and_return(['192.168.0.1','inet6:[::2]'])}
it { should run.with_params(['192.168.0.1','[::2]:80']).and_return(['192.168.0.1','inet6:[::2]:80'])}
it { should run.with_params(['192.168.0.1','::2']).and_return(['192.168.0.1','inet6:[::2]'])}
end