from __future__ import print_function import boto3 import json import botocore.exceptions as exceptions import urllib3 SUCCESS = "SUCCESS" FAILED = "FAILED" http = urllib3.PoolManager() def send(event, context, responseStatus, responseData, reason=None, physicalResourceId=None, noEcho=False): responseUrl = event['ResponseURL'] print(responseUrl) responseBody = { 'Status' : responseStatus, 'Reason' : reason or "See the details in CloudWatch Log Stream: {}".format(context.log_stream_name), 'PhysicalResourceId' : physicalResourceId or context.log_stream_name, 'StackId' : event['StackId'], 'RequestId' : event['RequestId'], 'LogicalResourceId' : event['LogicalResourceId'], 'NoEcho' : noEcho, 'Data' : responseData } json_responseBody = json.dumps(responseBody) print("Response body:") print(json_responseBody) headers = { 'content-type' : '', 'content-length' : str(len(json_responseBody)) } try: response = http.request('PUT', responseUrl, headers=headers, body=json_responseBody) print("Status code:", response.status) except Exception as e: print("send(..) failed executing http.request(..):", e) def getSubnetZoneId(): SubnetAZIdList = [] ec2 = boto3.client('ec2') Subnets = ec2.describe_subnets( Filters = [] ) for i in Subnets['Subnets']: SubnetAZIdDict={} SubnetAZIdDict['AvailabilityZoneId']=i['AvailabilityZoneId'] SubnetAZIdDict['CidrBlock']=i['CidrBlock'] SubnetAZIdDict['SubnetId'] = i['SubnetId'] SubnetAZIdList.append(SubnetAZIdDict) return SubnetAZIdList def load_az(azs,central_account_role): table={} if central_account_role == 'NoValue': dynamodb = boto3.resource('dynamodb') table = dynamodb.Table('AZsMapping') else: sts_connection = boto3.client('sts') acct_b = sts_connection.assume_role( RoleArn=central_account_role, RoleSessionName="cross_acct_lambda" ) ACCESS_KEY = acct_b['Credentials']['AccessKeyId'] SECRET_KEY = acct_b['Credentials']['SecretAccessKey'] SESSION_TOKEN = acct_b['Credentials']['SessionToken'] ddb = boto3.resource( 'dynamodb', aws_access_key_id=ACCESS_KEY, aws_secret_access_key=SECRET_KEY, aws_session_token=SESSION_TOKEN, ) table = ddb.Table('AZsMapping') for az in azs: azCode = az['AvailabilityZoneId'] cidrRange = az['CidrBlock'] print("Adding record:", azCode, cidrRange) print(az,type(az)) table.put_item(Item=az) def lambda_handler(event, context): try: responseData = {} print ('REQUEST BODY:n' + str(event)) CentralAccountRoles = event['ResourceProperties']['CentralAccountRoles'] SubnetAZIdList = getSubnetZoneId() print(SubnetAZIdList) load_az(SubnetAZIdList,CentralAccountRoles) responseStatus = SUCCESS except Exception as e: print (e) responseStatus = FAILED send(event, context, responseStatus, responseData)