-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathipv6subnets.py
77 lines (70 loc) · 2.38 KB
/
ipv6subnets.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
import cfnresponse
import ipaddress
import uuid
def subnetgenerator(event):
"""Generate IPv6 Subnets
Required keys inside event["ResourceProperties"]:
- Ipv6CidrBlock
Optional keys:
- Count (default: 1)
- Prefix (default: 64)
Args:
event(dict): Lambda function event
Returns:
list: List of strings (subnets)
"""
if "Ipv6CidrBlock" not in event["ResourceProperties"]:
raise Exception("No Ipv6CidrBlock specified")
ipv6cidrblock = ipaddress.IPv6Network(
unicode(event["ResourceProperties"]["Ipv6CidrBlock"]))
if "Prefix" not in event["ResourceProperties"]:
prefix = 64
else:
prefix = int(event["ResourceProperties"]["Prefix"])
if (prefix <= ipv6cidrblock.prefixlen):
raise Exception("Prefix must be higher than '{prefixlen}'".format(
prefixlen=ipv6cidrblock.prefixlen))
if "Count" not in event["ResourceProperties"]:
count = 1
event["ResourceProperties"] = 1
else:
count = int(event["ResourceProperties"]["Count"])
subnets = []
for subnet in ipv6cidrblock.subnets(new_prefix=prefix):
if count == 0:
break
subnets.append(str(subnet))
count -= 1
if count > 0:
raise Exception("Chosen prefix '{prefixlen}' doesn't allow the "
"creation of the requested '{count}' subnets".format(
prefixlen=ipv6cidrblock.prefixlen,
count=event["ResourceProperties"]["Count"]))
return(subnets)
def lambda_handler(event, context):
if event["RequestType"] in ["Create", "Update"]:
try:
subnets = subnetgenerator(event)
except:
cfnresponse.send(
event,
context,
cfnresponse.FAILED,
None,
event["PhysicalResourceId"] or None)
return
cfnresponse.send(
event,
context,
cfnresponse.SUCCESS,
{"Subnets": subnetgenerator(event)},
str(uuid.uuid4()))
elif event["RequestType"] == "Delete":
cfnresponse.send(
event,
context,
cfnresponse.SUCCESS,
None,
event["PhysicalResourceId"])
else:
raise Exception("Unknown RequestType %s" % (event["RequestType"]))