code-dumps/py/nextSubnetLambda.py
2020-07-02 11:36:28 +08:00

39 lines
971 B
Python

"""
To use this function in lambda, one needs to upload netaddr and this code as a package. here is how
pip3 install netaddr -t ./
zip -r ../acrolinxNextSubnet.zip .
"""
from netaddr import *
import boto3
import cfnresponse
import json
import os
def lambda_handler(event, context):
my_vpc = {
'eu-west-1': 'vpc-55a5a930',
'us-west-2': 'vpc-7155ca14'
}
session = boto3.session.Session()
my_region = session.region_name
ec2 = session.resource('ec2')
vpc = ec2.Vpc(my_vpc[my_region])
subnets = []
for subnet in vpc.subnets.all():
subnets.append(IPNetwork(subnet.cidr_block))
lastSubnet = sorted(subnets).pop()
nextSubnet = str(lastSubnet.next())
return {
'region': my_region,
'body': json.dumps(nextSubnet)
}
# response_data = {}
# response_data = {"cidr": nextSubnet}
# my_data = nextSubnet
# cfnresponse.send(event,context,cfnresponse.SUCCESS, response_data, my_data)