Skip to content

Commit

Permalink
add to inventory.py script ability to indicate ip ranges (kubernetes-…
Browse files Browse the repository at this point in the history
…sigs#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
  • Loading branch information
tikitavi authored and mattymo committed Feb 6, 2019
1 parent 69e5dee commit 263c873
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 0 deletions.
21 changes: 21 additions & 0 deletions contrib/inventory_builder/inventory.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,7 @@ def __init__(self, changed_hosts=None, config_file=None):
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)
Expand Down Expand Up @@ -179,6 +180,26 @@ def build_hostnames(self, changed_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):
return hostname in existing_hosts.keys()

Expand Down
11 changes: 11 additions & 0 deletions contrib/inventory_builder/tests/test_inventory.py
Original file line number Diff line number Diff line change
Expand Up @@ -238,3 +238,14 @@ def test_scale_scenario_two(self):
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)

0 comments on commit 263c873

Please sign in to comment.