add to inventory.py script ability to indicate ip ranges (#4182)

* add to inventory.py script ability to indicate ip ranges

* add test for range2ip function for inventory.py script

some fixes

* add negative test for range2ip function for inventory.py script
This commit is contained in:
tikitavi 2019-02-06 18:22:13 +03:00 committed by Matthew Mosesohn
parent 69e5deeccc
commit 263c8731f2
2 changed files with 32 additions and 0 deletions

View file

@ -81,6 +81,7 @@ class KubesprayInventory(object):
self.ensure_required_groups(ROLES) self.ensure_required_groups(ROLES)
if changed_hosts: if changed_hosts:
changed_hosts = self.range2ips(changed_hosts)
self.hosts = self.build_hostnames(changed_hosts) self.hosts = self.build_hostnames(changed_hosts)
self.purge_invalid_hosts(self.hosts.keys(), PROTECTED_NAMES) self.purge_invalid_hosts(self.hosts.keys(), PROTECTED_NAMES)
self.set_all(self.hosts) self.set_all(self.hosts)
@ -179,6 +180,26 @@ class KubesprayInventory(object):
return all_hosts return all_hosts
def range2ips(self, hosts):
from ipaddress import ip_address
reworked_hosts = []
def ips(start_address, end_address):
start = int(ip_address(start_address).packed.hex(), 16)
end = int(ip_address(end_address).packed.hex(), 16)
return [ip_address(ip).exploded for ip in range(start, end+1)]
for host in hosts:
if '-' in host:
start, end = host.strip().split('-')
try:
reworked_hosts.extend(ips(start, end))
except ValueError:
raise Exception("Range of ip_addresses isn't valid")
else:
reworked_hosts.append(host)
return reworked_hosts
def exists_hostname(self, existing_hosts, hostname): def exists_hostname(self, existing_hosts, hostname):
return hostname in existing_hosts.keys() return hostname in existing_hosts.keys()

View file

@ -238,3 +238,14 @@ class TestInventory(unittest.TestCase):
self.inv.set_kube_node(hosts.keys()) self.inv.set_kube_node(hosts.keys())
for h in range(5): for h in range(5):
self.assertFalse(hosts.keys()[h] in self.inv.config['kube-node']) self.assertFalse(hosts.keys()[h] in self.inv.config['kube-node'])
def test_range2ips_range(self):
changed_hosts = ['10.90.0.2', '10.90.0.4-10.90.0.6', '10.90.0.8']
expected = ['10.90.0.2', '10.90.0.4', '10.90.0.5', '10.90.0.6', '10.90.0.8']
result = self.inv.range2ips(changed_hosts)
self.assertEqual(expected, result)
def test_range2ips_incorrect_range(self):
host_range = ['10.90.0.4-a.9b.c.e']
self.assertRaisesRegexp(Exception, "Range of ip_addresses isn't valid",
self.inv.range2ips, host_range)