diff --git a/contrib/inventory_builder/inventory.py b/contrib/inventory_builder/inventory.py index abd9cd021..df1307f78 100644 --- a/contrib/inventory_builder/inventory.py +++ b/contrib/inventory_builder/inventory.py @@ -81,6 +81,7 @@ class KubesprayInventory(object): self.ensure_required_groups(ROLES) if changed_hosts: + changed_hosts = self.range2ips(changed_hosts) self.hosts = self.build_hostnames(changed_hosts) self.purge_invalid_hosts(self.hosts.keys(), PROTECTED_NAMES) self.set_all(self.hosts) @@ -179,6 +180,26 @@ class KubesprayInventory(object): 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): return hostname in existing_hosts.keys() diff --git a/contrib/inventory_builder/tests/test_inventory.py b/contrib/inventory_builder/tests/test_inventory.py index 43f6b2bb6..cb108c821 100644 --- a/contrib/inventory_builder/tests/test_inventory.py +++ b/contrib/inventory_builder/tests/test_inventory.py @@ -238,3 +238,14 @@ class TestInventory(unittest.TestCase): self.inv.set_kube_node(hosts.keys()) for h in range(5): 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)