-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsubnets_maths.py
93 lines (76 loc) · 1.79 KB
/
subnets_maths.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
#!/usr/bin/env python
"""
POC for subnet calculator
"""
import ipaddress
from math import (
log,
ceil
)
pow2_2_prefix = {
'16': 28,
'32': 27,
'64': 26,
'128': 25,
'256': 24,
'512': 23,
'1024': 22,
'2048': 21,
'4096': 20,
'8192': 19,
'16384': 18,
'32768': 17,
'65536': 16,
'131072': 15,
'262144': 14,
'524288': 13,
'1048576': 12,
'2097152': 11,
'4194304': 10,
'8388608': 9,
'16777216': 8
}
clpow2 = lambda x: pow(2, int(log(x, 2) + 0.5))
nxtpow2 = lambda x: int(pow(2, ceil(log(x, 2))))
def cut_per_az(az_cidr, layers_cidr):
"""
"""
maj_splits = list(az_cidr.subnets(prefixlen_diff=1))
layers_cidr['app'].append(maj_splits[0])
min_splits = list(maj_splits[1].subnets(prefixlen_diff=1))
layers_cidr['pub'].append(min_splits[0])
layers_cidr['stor'].append(min_splits[1])
def get_subnets(cidr, azs):
"""
Main function
"""
cidr = f'{cidr}'
vpc_net = ipaddress.IPv4Network(cidr)
number_ips = int(vpc_net.num_addresses - 2)
if (azs != 2) and (azs % 2):
azs += 1
layers_cidr = {
'app' : [],
'pub': [],
'stor': []
}
ips_per_az = number_ips / azs
pow2 = clpow2(ips_per_az)
azs_prefix = pow2_2_prefix['%d' % (pow2)]
subnets_per_az = list(vpc_net.subnets(new_prefix=azs_prefix))
for az in subnets_per_az:
cut_per_az(az, layers_cidr)
return layers_cidr
def get_subnet_layers(cidr, azs):
"""
Returns Dictionary of the CIDRs per layer name
"""
layers = get_subnets(cidr, azs)
cidrs = {}
for layer in layers:
cidrs[layer] = []
sub_list = []
for subnet in layers[layer]:
sub_list.append('%s' % (subnet))
cidrs[layer] = sub_list
return cidrs