def lambda_handler(event,context):
    logger.info("Got Event: {}".format(event))
    try:
        config = fetchFromTransitConfigTable(transitConfigTable)
        logger.info("Got config: {}".format(config))
        if config:
            #deleteVpnConfigurationFromPaGroup() this will be from pan_vpn_generic file
            vpcResult = getItemFromVpcTable(config['TransitVpcTable'],event['VpcId'])
            logger.info("Got vpcResult: {}".format(vpcResult))
            if vpcResult:
                paGroupResult = getItemFromPaGroupInfo(config['TransitPaGroupInfo'],vpcResult['PaGroupName'])
                if paGroupResult:
                    api_key = pan_vpn_generic.getApiKey(paGroupResult['N1Mgmt'], config['UserName'],config['Password'])
                    #Deleting the VPN connections with the PA Group
                    pan_vpn_generic.paGroupDeleteVpn(api_key, paGroupResult, vpcResult['Node1VpnId'],vpcResult['Node2VpnId'])
                    logger.info("Successfully deleted VPN connections VPN1: {}, VPN2: {} with PaGroup: {} ".format(vpcResult['Node1VpnId'],vpcResult['Node2VpnId'],paGroupResult['PaGroupName']))
                    #Delete Item from TransitVpcTable with
                    deleteItemFromVpcTable(config['TransitVpcTable'],event['VpcId'])
                    updatePaGroupInfoTable(config['TransitPaGroupInfo'],vpcResult['PaGroupName'])
                    updateBgpTunnleIpPool(config['TransitBgpTunnelIpPool'], event['VpcId'])
                    if 'VgwAsn' in event: updateVgwAsn(config['TransitVgwAsn'],event['VgwAsn'])
        else:
            logger.error("Not Received any data from TransitConfig table")
    except Exception as e:
        logger.error("Error from deleteTransitVpnConfiguration, Error: {}".format(str(e)))
Example #2
0
def lambda_handler(event, context):
    logger.info('Got Event {}'.format(event))

    config = fetchFromTransitConfigTable(transitConfigTable)
    if config:
        paGroupInfo = getPaGroupInfo(config['TransitPaGroupInfo'],
                                     event['PaGroupName'])
        if paGroupInfo:
            api_key = pan_vpn_generic.getApiKey(paGroupInfo['N1Mgmt'],
                                                config['UserName'],
                                                config['Password'])
            paVpnStatus = pan_vpn_generic.paGroupConfigureVpn(
                api_key, paGroupInfo, config['TransitVpnBucketName'],
                event['VpnN1'], event['VpnN2'])
            if paVpnStatus:
                updateVpcTable(config['TransitVpcTable'], event, 'Configured')
                updateVgwAsn(config['TransitVgwAsn'], event['VpcId'],
                             event['VgwAsn'])
                data = {
                    'Action': 'VpnConfigured',
                    'VpcId': event['VpcId'],
                    'PaGroupName': event['PaGroupName'],
                    'Rebalance': event['Rebalance'],
                    'Region': event['Region']
                }
                logger.info('Publishing message to Subscriber SNS with '
                            'data: {}'.format(data))
                publishToSns(event['SubscriberSnsArn'], data,
                             event['SubscriberAssumeRoleArn'])
            else:
                updatePaGroup(config['TransitPaGroupInfo'],
                              event['PaGroupName'], -1)
                updateBgpTunnelIpPool(config['TransitBgpTunnelIpPool'],
                                      event['IpSegment'])
                updateVpcTable(config['TransitVpcTable'], event, 'Failed')
                updateVgwAsn(config['TransitVgwAsn'], event['VpcId'],
                             event['VgwAsn'])
                # Publish Message to SubscriberSns
                data = {
                    'Action': 'VpnFailed',
                    'Rebalance': event['Rebalance'],
                    'VpcId': event['VpcId'],
                    'Region': event['Region']
                }
                logger.info('Publishing message to Subscriber SNS with '
                            'data: {}'.format(data))
                publishToSns(event['SubscriberSnsArn'], data,
                             event['SubscriberAssumeRoleArn'])
        else:
            logger.error('No Item received from PaGroupInfo table with '
                         'Key: {}'.format(event['PaGroupName']))
    else:
        logger.error('Not Received any data from TransitConfig table')
Example #3
0
def lambda_handler(event,context):
    logger.info("Got Event {}".format(event))
    #username = "******"
    #password = "******"
    config = fetchFromTransitConfigTable(transitConfigTable)
    if config:
        paGroupInfo = getPaGroupInfo(config['TransitPaGroupInfo'],event['PaGroupName'])
        if paGroupInfo:
            api_key = pan_vpn_generic.getApiKey(paGroupInfo['N1Mgmt'], config['UserName'], config['Password'])
            paVpnStatus = pan_vpn_generic.paGroupConfigureVpn(api_key, paGroupInfo, config['TransitVpnBucketName'], event['VpnN1'],event['VpnN2'])
            if paVpnStatus:
                updateVpcTable(config['TransitVpcTable'],event,'Configured')
                updateVgwAsn(config['TransitVgwAsn'],event['VpcId'],event['VgwAsn'])
                data={
                    'Action': 'VpnConfigured',
                    'VpcId': event['VpcId'],
                    'PaGroupName': event['PaGroupName'],
                    'Rebalance': event['Rebalance'],
                    'Region': event['Region']
                }
                logger.info("Publishing message to Subscriber SNS with data: {}".format(data))
                publishToSns(event['SubscriberSnsArn'], data, event['SubscriberAssumeRoleArn'])
            else:
                updatePaGroup(config['TransitPaGroupInfo'],event['PaGroupName'], -1)
                updateBgpTunnelIpPool(config['TransitBgpTunnelIpPool'],event['IpSegment'])
                updateVpcTable(config['TransitVpcTable'],event,'Failed')
                updateVgwAsn(config['TransitVgwAsn'],event['VpcId'],event['VgwAsn'])
                #Publish Message to SubscriberSns
                data={
                    'Action': 'VpnFailed',
                    'Rebalance': event['Rebalance'],
                    'VpcId': event['VpcId'],
                    'Region': event['Region']
                }
                logger.info("Publishing message to Subscriber SNS with data: {}".format(data))
                publishToSns(event['SubscriberSnsArn'], data, event['SubscriberAssumeRoleArn'])
                #updateVgwAsnTable(config['TransitVgwAsn'],event['VpcId']) #Is this needed, since we are checking for whether vgw is attached to VPC or not in fetchVpnServerDetails
        else:
            logger.error("No Item received from PaGroupInfo table with Key: {}".format(event['PaGroupName']))
    else:
        logger.error("Not Received any data from TransitConfig table")
Example #4
0
def lambda_handler(event, context):
    logger.info("Got Event {}".format(event))
    testparams = event['queryStringParameters']
    logger.info("Got query parameter {}".format(testparams))
    config = fetchFromTransitConfigTable(transitConfigTable)
    filecontents = downloadFileFromS3(
        event['queryStringParameters']['messagefileName'],
        config['TransitVpnBucketName'])
    logger.info(
        'Downloaded from S3 object and Result is {} '.format(filecontents))
    creds = get_secret(secretName, endpointUrl, region)
    username = creds['username']
    password = creds['password']

    if config:
        paGroupInfo = getPaGroupInfo(config['TransitPaGroupInfo'],
                                     filecontents['PaGroupName'])
        if paGroupInfo:
            api_key = pan_vpn_generic.getApiKey(paGroupInfo['N1Mgmt'],
                                                username, password)
            logger.info("Got api_key: {}".format(api_key))
            paVpnStatus = pan_vpn_generic.paGroupConfigureVpn(
                api_key, paGroupInfo, config['TransitVpnBucketName'],
                filecontents['VpnN1'], filecontents['VpnN2'])
            logger.info("Got paVpnStatus: {}".format(paVpnStatus))
            if paVpnStatus:
                updateVpcTable(config['TransitVpcTable'], filecontents,
                               'Configured')
                logger.info("Updated Table: {}".format(
                    config['TransitVpcTable']))
                updateVgwAsn(config['TransitVgwAsn'], filecontents['VpcId'],
                             filecontents['vgwAsn'])
                logger.info("Updated Table: {}".format(
                    config['TransitVgwAsn']))
                data = {
                    'Action': 'VpnConfigured',
                    'VpcId': filecontents['VpcId'],
                    'PaGroupName': filecontents['PaGroupName'],
                    'Region': 'eu-west-1'
                }
                logger.info("Returning data: {}".format(data))

                apioutput = response(data, 200)
                logger.info("Sending response={}, hence proceeding  ".format(
                    apioutput))
                return apioutput
            else:
                updatePaGroup(config['TransitPaGroupInfo'],
                              filecontents['PaGroupName'], -1)
                updateBgpTunnelIpPool(config['TransitBgpTunnelIpPool'],
                                      filecontents['IpSegment'])
                updateVpcTable(config['TransitVpcTable'], filecontents,
                               'Failed')
                updateVgwAsn(config['TransitVgwAsn'], filecontents['VpcId'],
                             filecontents['vgwAsn'])
                #Publish Message to SubscriberSns
                data = {
                    'Action': 'VpnFailed',
                    'VpcId': filecontents['VpcId'],
                    'Region': filecontents['Region']
                }
                logger.info("Sendig response data: {}".format(data))
                apioutput = response(data, 200)
                logger.info("Sending response={}, hence terminating  ".format(
                    apioutput))
                return apioutput

        else:
            logger.error(
                "No Item received from PaGroupInfo table with Key: {}".format(
                    filecontents['PaGroupName']))
    else:
        logger.error("Not Received any data from TransitConfig table")
def lambda_handler(event, context):
    logger.info("Got Event {}".format(event))
    config = fetchFromTransitConfigTable(transitConfigTable)

    if config:
        stackStatus = pan_vpn_generic.parseStackOutput(event['StackName'],
                                                       event['Region'])
        logger.info("Stack Status: {}".format(stackStatus))

        if 'PaGroupName' in stackStatus:
            panStatus = pan_vpn_generic.checkPaGroupReady(
                config['UserName'], config['Password'], stackStatus)

            if panStatus:
                logger.info("PaGroup: {} is ready".format(
                    stackStatus['PaGroupName']))
                logger.info("Initializing the PA Servers")
                api_key = pan_vpn_generic.getApiKey(stackStatus['N1Mgmt'],
                                                    config['UserName'],
                                                    config['Password'])
                initPaServersStatus = pan_vpn_generic.paGroupInitialize(
                    api_key, stackStatus, config['DeLicenseApiKey'])

                if initPaServersStatus:

                    logger.info(
                        "Initialization of PA Servers is Success, response: {}"
                        .format(initPaServersStatus))
                    logger.info(
                        "Updating PaGroupInfoTable with PaGroup, N1Mgmt, N2Mgmt, N1Eip, N2Eip and VpcCount=0"
                    )
                    updatePaGroup(config['TransitPaGroupInfo'], stackStatus,
                                  event['Region'])
                    import time
                    time.sleep(5)
                    logger.info(
                        "Peering of PA Groups with new PAGroup initiated")
                    configurePaPeers(config['TransitPaGroupInfo'], api_key,
                                     stackStatus)
                    event['Action'] = 'Success'
                    return event
                else:
                    logger.info(
                        "Initialization of PA Servers is failed, Error {}".
                        format(initPaServerStatus))
                    event[
                        'Action'] = 'Error While Initializing the PA Server {}'.format(
                            stackStatus)
                    return event
            else:
                logger.info("PaGroup: {} is NOT ready".format(
                    stackStatus['PaGroupName']))
                event['Action'] = 'Wait'
                return event
        elif stackStatus == "Wait":
            event['Action'] = 'Wait'
            return event
        else:
            updateConfigDb(event['StackName'])
            return
    else:
        logger.error("Not Received any data from TransitConfig table")
        return
def lambda_handler(event, context):
    logger.info("Got Event: {}".format(event))
    config = fetchFromTransitConfigTable(transitConfigTable)
    if config:
        response = getInUsePaGroups(config['TransitPaGroupInfo'],
                                    int(config['PaGroupMaxVpc']))
        if response:
            if config['RebalanceInProgress'] == 'True':
                if config['RebalanceStatus'] == 'Done':
                    apiKey = pan_vpn_generic.getApiKey(response[0]['N1Mgmt'],
                                                       config['UserName'],
                                                       config['Password'])
                    result = rebalance.rebalance(apiKey, response,
                                                 int(config['PaGroupMaxVpc']),
                                                 config)
                    if result:
                        # Get the VGW, Region, SubscriberSnsArn and SubscriberAssumeRoleArn from VpcTable
                        subscriberData = getSubscriberDataFromVpcTable(
                            config['TransitVpcTable'],
                            result['FromPaGroup']['PaGroupName'])
                        result['FromPaGroup']['VpcCount'] = str(
                            result['FromPaGroup']['VpcCount'])
                        result['ToPaGroup']['VpcCount'] = str(
                            result['ToPaGroup']['VpcCount'])
                        value = {
                            'FromPaGroupName':
                            result['FromPaGroup']['PaGroupName'],
                            'ToPaGroupName':
                            result['ToPaGroup']['PaGroupName'],
                            'VpcId':
                            subscriberData['VpcId'],
                            'VpcCidr':
                            subscriberData['VpcCidr'],
                            'Region':
                            subscriberData['Region'],
                            'SubscriberSnsArn':
                            subscriberData['SubscriberSnsArn'],
                            'SubscriberAssumeRoleArn':
                            subscriberData['SubscriberAssumeRoleArn'],
                            'CreateStatus':
                            'Pending',
                            'DeleteStatus':
                            'InProgress'
                        }
                        item = {'Property': 'RebalanceStatus', 'Value': value}
                        updateTransitConfig(transitConfigTable, item)
                        # Send DeleteOperatin first
                        deleteData = {
                            'Action': 'DeleteVpnConnection',
                            'VpcId': subscriberData['VpcId'],
                            'Region': subscriberData['Region'],
                            'Rebalance': 'True'
                        }
                        #Publish message to Transit SNS
                        publishToSns(subscriberData['SubscriberSnsArn'],
                                     deleteData,
                                     subscriberData['SubscriberAssumeRoleArn'])
                        logger.info(
                            "Published message to Subscriber SNS with data: {}"
                            .format(deleteData))
                        return
                else:
                    previousTaskStatus = config['RebalanceStatus']
                    if previousTaskStatus['DeleteStatus'] == 'InProgress':
                        vpcStatus = checkVpcIdInVpcTable(
                            config['TransitVpcTable'],
                            previousTaskStatus['VpcId'])
                        logger.info("Got VPC Status: {}".format(vpcStatus))
                        if len(vpcStatus['Items']) > 0:
                            if vpcStatus['Items'][0][
                                    'PaGroupName'] == previousTaskStatus[
                                        'FromPaGroupName']:
                                logger.info(
                                    "Previous Delete VPN Operation is still InProgress, hence exiting from the process"
                                )
                                return
                        else:
                            # Create FetchVpnServerDetails and send to Subscriber SNS
                            previousTaskStatus['CreateStatus'] = 'InProgress'
                            previousTaskStatus['DeleteStatus'] = 'Completed'
                            item = {
                                'Property': 'RebalanceStatus',
                                'Value': previousTaskStatus
                            }
                            updateTransitConfig(transitConfigTable, item)

                            data = {
                                'Action':
                                'FetchVpnServerDetails',
                                'Region':
                                previousTaskStatus['Region'],
                                'VpcId':
                                previousTaskStatus['VpcId'],
                                'SubscriberAssumeRoleArn':
                                previousTaskStatus['SubscriberAssumeRoleArn'],
                                'SubscriberSnsArn':
                                previousTaskStatus['SubscriberSnsArn'],
                                'VpcCidr':
                                previousTaskStatus['VpcCidr'],
                                'Rebalance':
                                'True'
                            }
                            #Publish message to Transit SNS
                            publishToSns(config['TransitSnsArn'], data)
                            logger.info(
                                "Published message to Transit SNS with data: {}"
                                .format(data))
                            return
                    elif previousTaskStatus['CreateStatus'] == 'InProgress':
                        logger.info(
                            "Previous task was CreateTask, now check whether it has completed or not"
                        )
                        vpcStatus = checkVpcIdInVpcTable(
                            config['TransitVpcTable'],
                            previousTaskStatus['VpcId'])
                        logger.info("Got VPC Status: {}".format(vpcStatus))
                        if not vpcStatus['Items']:
                            logger.info(
                                "Create Task is still in progress, hence exiting"
                            )
                            return
                        else:
                            if vpcStatus['Items'][0][
                                    'PaGroupName'] == previousTaskStatus[
                                        'ToPaGroupName']:
                                logger.info(
                                    "Previous Rebalance task Completed successfully, updating the RebalanceStatus=Done"
                                )
                                item = {
                                    'Property': 'RebalanceStatus',
                                    'Value': 'Done'
                                }
                                updateTransitConfig(transitConfigTable, item)
                                return
                            else:
                                logger.error(
                                    "Something terrible happened? Unknown status, Stop StateMachine and Exit"
                                )
                                #Something terrible happened? Unknown status, Stop StateMachine and Exit
                                return
        else:
            logger.info("No PaGroups for Rebalancing, PaGroups are Optimal")
    else:
        logger.error("Not Received any data from TransitConfig table")
def lambda_handler(event, context):
    if 'queryStringParameters' in event.keys():
        event = event['queryStringParameters']
    logger.info("Got Event: {}".format(event))
    try:
        config = fetchFromTransitConfigTable(transitConfigTable)
        creds = get_secret(secretName,endpointUrl,region)
        logger.info("Got creds {}".format(creds))
        username = creds['username']
        password = creds['password']
        logger.info("Got config: {}".format(config))
        if config:
            # deleteVpnConfigurationFromPaGroup() this will be from pan_vpn_generic file
            vpcResult = getItemFromVpcTable(config['TransitVpcTable'], event['VpcId'])
            logger.info("Got vpcResult from {} table {}".format(vpcResult, config['TransitVpcTable']))
            if vpcResult:
                paGroupResult = getItemFromPaGroupInfo(config['TransitPaGroupInfo'], vpcResult['PaGroupName'])
                logger.info('Got paGroupResult {} from {}'.format(paGroupResult, config['TransitPaGroupInfo']))
                if paGroupResult:
                    api_key = pan_vpn_generic.getApiKey(paGroupResult['N1Mgmt'], username, password)
                    logger.info('Got apikey ')
                    # Deleting the VPN connections with the PA Group
                    logger.info('Calling paGroupDeleteVpn with {} {} {}'.format(paGroupResult, vpcResult['Node1VpnId'],
                                                                                vpcResult['Node2VpnId']))
                    pan_vpn_generic.paGroupDeleteVpn(api_key, paGroupResult, vpcResult['Node1VpnId'],
                                                     vpcResult['Node2VpnId'])
                    logger.info("Successfully deleted VPN connections VPN1: {}, VPN2: {} with PaGroup: {} ".format(
                        vpcResult['Node1VpnId'], vpcResult['Node2VpnId'], paGroupResult['PaGroupName']))
                    # Delete Item from TransitVpcTable with
                    res = deleteItemFromVpcTable(config['TransitVpcTable'], event['VpcId'])
                    logger.info('Deleted Item from table {}'.format(config['TransitVpcTable']))
                    updatePaGroupInfoTable(config['TransitPaGroupInfo'], vpcResult['PaGroupName'])

                    updateBgpTunnleIpPool(config['TransitBgpTunnelIpPool'], event['VpcId'])
                    if 'VpcId' in event:
                        updateVgwAsn(config['TransitVgwAsn'], event['VpcId'])
                        logger.info('Deleted VgwAsn from table {}'.format(config['TransitVgwAsn']))
                    data1 = {
                        'Result': 'Success',
                        'Reason': 'Updated deleted the VPN and updated the tables' + config['TransitVpcTable']
                    }
                    apioutput = response(data1, 200)
                    logger.info("Sending response={}, hence proceeding  ".format(apioutput))
                    return apioutput
                else:
                    logger.info("Sending response={}, hence proceeding  ".format(apioutput))
                    data2 = {
                        'Result': 'Success',
                        'Reason': 'No Items matched with the GroupName: {}' + vpcResult['PaGroupName']
                    }
                    apioutput = response(data2, 200)
                    return apioutput
            else:
                data3 = {
                    'Result': 'Failure',
                    'Reason': "No Item matched with VpcId {}".format(event['VpcId'])
                }
                apioutput = response(data3, 200)
                return apioutput
        else:
            logger.error("Not Received any data from TransitConfig table")
    except Exception as e:
        logger.error("Error from deleteTransitVpnConfiguration, Error: {}".format(str(e)))