def main()

in resources/AccountCreationLambda.py [0:0]


def main(event,context):
    print(event)
    client = get_client('organizations')
    ec2_client = get_client('ec2')
    accountname = event['ResourceProperties']['AccountName']
    accountemail = event['ResourceProperties']['AccountEmail']
    organization_unit_name = event['ResourceProperties']['OrganizationalUnitName']
    accountrole = 'OrganizationAccountAccessRole'
    stackname = event['ResourceProperties']['StackName']
    stackregion = event['ResourceProperties']['StackRegion']
    ServiceCatalogUserName = event['ResourceProperties']['ServiceCatalogUserName']
    ServiceCatalogUserPassword = event['ResourceProperties']['ServiceCatalogUserPassword']
    sourcebucket = event['ResourceProperties']['SourceBucket']
    baselinetemplate = event['ResourceProperties']['BaselineTemplate']
    access_to_billing = "DENY"
    scp = None

    if (event['RequestType'] == 'Create'):
        top_level_account = event['ServiceToken'].split(':')[4]
        print("The top level account is "+top_level_account)
        org_client = get_client('organizations')

        try:
            list_roots_response = org_client.list_roots()
            root_id = list_roots_response['Roots'][0]['Id']
        except:
            root_id = "Error"

        if root_id  is not "Error":
            try:
                #Create new account
                print("Creating new account: " + accountname + " (" + accountemail + ")")
                (create_account_response,account_id) = create_account(accountname,accountemail,accountrole,access_to_billing,scp,root_id)
                print(create_account_response)
                print("Created account:{}\n".format(account_id))
                time.sleep(20)
            except:
                print("Error creating new account..")
                sys.exit(0)

            #Create resources in the newly vended account
            try:
                #Move account to OU provided
                if(organization_unit_name!='None'):
                    try:
                        (organization_unit_name,organization_unit_id) = get_ou_name_id(event, root_id,organization_unit_name)
                        move_response = org_client.move_account(AccountId=account_id,SourceParentId=root_id,DestinationParentId=organization_unit_id)
                    except botocore.exceptions.ClientError as e:
                        print("An error occured. Org account move response: {} . Error Stack: {}".format(move_response, e))
                        sys.exit(0)
                credentials = assume_role(account_id, accountrole)
                template = get_template(sourcebucket,baselinetemplate)

                #deploy cloudformation template (AccountBaseline.yml)
                stack = deploy_resources(credentials, template, stackname, stackregion, ServiceCatalogUserName, ServiceCatalogUserPassword,account_id)
                print(stack)
                print("Baseline setup deployment for account " + account_id + " (" + accountemail + ") complete!")

                #delete default vpc in every region
                regions = []
                regions_response = ec2_client.describe_regions()
                for i in range(0,len(regions_response['Regions'])):
                    regions.append(regions_response['Regions'][i]['RegionName'])
                for r in regions:
                    try:
                        delete_vpc_response = delete_default_vpc(credentials,r)
                    except botocore.exceptions.ClientError as e:
                        print("An error occured while deleting Default VPC in {}. Error: {}".format(r,e))
                        i+=1
                respond_cloudformation(event, "SUCCESS", { "Message": "Account created successfully", "AccountID" : account_id, "LoginURL" : "https://" +account_id+".signin.aws.amazon.com/console", "Username" : ServiceCatalogUserName })
            except botocore.exceptions.ClientError as e:
                print("An error occured. Error Stack: {}".format(e))
                sys.exit(0)

    if(event['RequestType'] == 'Update'):
        print("Template in Update Status")
        respond_cloudformation(event, "SUCCESS", { "Message": "Resource update successful!" })

    elif(event['RequestType'] == 'Delete'):
        try:
            delete_respond_cloudformation(event, "SUCCESS", {"Message":"Delete Request Initiated. Deleting Lambda Function."})
        except:
            print("Couldnt initiate delete response.")