Exemplo n.º 1
0
def handle_ec2_terminate_event(instance_id):
    """
    Purpose:    Handler for EC2 terminate event
    Parameters: Instance Id
    Returns:
    Raises:
    """
    utl.put_line_in_log('EC2 Terminate Handler', 'thin')
    logger.info("Received EC2 termination notification for instance-id: " +
                str(instance_id))

    # SNS class initialization
    sns = SimpleNotificationService()

    if instance_id is not None:  # Since Instance termination initiated, delete entries
        logger.info("Instance termination has been initiated: " + instance_id)
        logger.info("Initiating vm_delete function via SNS")
        message_subject = 'EVENT: ' + utl.e_var[
            'AutoScaleGrpName'] + ' ' + 'instance delete' + ' ' + instance_id
        sns.publish_to_topic(utl.e_var['AutoScaleManagerTopic'],
                             'VM not accessible', message_subject, 'vm_delete',
                             'FIRST', instance_id)
    utl.put_line_in_log('EC2 Terminate Handler finished', 'thin')
    return
Exemplo n.º 2
0
def handle_ec2_launch_event(instance_id):
    """
    Purpose:    Handler for EC2 launch event
    Parameters: Instance Id
    Returns:
    Raises:
    """
    utl.put_line_in_log('EC2 Launch Handler', 'thin')
    if instance_id is not None:
        logger.info("Received EC2 launch notification for instance-id: " +
                    str(instance_id))

        # SNS class initialization
        sns = SimpleNotificationService()

        # FTD class initialization
        instance = NgfwInstance(instance_id)
        instance_state = instance.get_instance_state()
        interfaces_ip = instance.get_instance_interfaces_ip()
        if interfaces_ip is None:
            logger.warn("Unable to get IPs of the instance" + instance_id)
            message_subject = 'EVENT: ' + utl.e_var[
                'AutoScaleGrpName'] + ' ' + 'instance poll' + ' ' + instance_id
            sns.publish_to_topic(utl.e_var['AutoScaleManagerTopic'],
                                 'Check VM is ready', message_subject,
                                 'vm_ready', 'FIRST', instance_id)
            utl.put_line_in_log('EC2 Launch Handler finished', 'thin')
            return

        if instance_state == 'running' or instance_state == 'pending':
            logger.info("Instance %s is in state: %s" %
                        (instance_id, instance_state))
            message_subject = 'EVENT: ' + utl.e_var[
                'AutoScaleGrpName'] + ' ' + 'instance poll' + ' ' + instance_id
            sns.publish_to_topic(utl.e_var['AutoScaleManagerTopic'],
                                 'Check VM is ready', message_subject,
                                 'vm_ready', 'FIRST', instance_id)
        else:
            logger.warn("Instance %s is in state: %s" %
                        (instance_id, instance_state))
    else:
        logger.critical("Received instance_id None!")
    utl.put_line_in_log('EC2 Launch Handler finished', 'thin')
    return
Exemplo n.º 3
0
def handle_ec2_terminate_event(instance_id):
    """
    Purpose:    Handler for EC2 terminate event
    Parameters: Instance Id
    Returns:
    Raises:
    """
    utl.put_line_in_log('EC2 Terminate Handler', 'thin')
    logger.info("Received EC2 termination notification for instance-id: " +
                str(instance_id))

    # SNS class initialization
    sns = SimpleNotificationService()

    if instance_id is not None:  # Since Instance termination initiated, delete entries
        logger.info("Instance termination has been initiated: " + instance_id)
        logger.info("Initiating vm_delete function via SNS")

        if not const.DISABLE_VM_DELETE_FUNC:
            message_subject = 'Event: ' + e_var[
                'AutoScaleGrpName'] + ' ' + 'instance delete' + ' ' + instance_id
            msg_body = utl.sns_msg_body_configure_ftdv_topic(
                'vm_delete', 'FIRST', instance_id)
            sns.publish_to_topic(e_var['AutoScaleManagerTopic'],
                                 message_subject, msg_body)

        if e_var['USER_NOTIFY_TOPIC_ARN'] is not None:
            # Email to user
            details_of_the_device = None
            message_subject = 'Event: ' + e_var['AutoScaleGrpName'] + ' ' + instance_id + ' ' + \
                              'instance is terminated'
            msg_body = utl.sns_msg_body_user_notify_topic(
                'VM Terminated', e_var['AutoScaleGrpName'], instance_id,
                details_of_the_device)
            sns.publish_to_topic(e_var['USER_NOTIFY_TOPIC_ARN'],
                                 message_subject, msg_body)
            # -------------
    utl.put_line_in_log('EC2 Terminate Handler finished', 'thin')
    return
Exemplo n.º 4
0
def handle_sns_event(sns_data):
    """
    Purpose:    Handler for SNS event
    Parameters: SNS data from Lambda handler
    Returns:
    Raises:
    """
    utl.put_line_in_log('SNS Handler', 'thin')
    logger.debug("SNS Message: " + json.dumps(sns_data, separators=(',', ':')))

    # SNS class initialization
    sns = SimpleNotificationService()

    sns_msg_attr = json.loads(sns_data['Message'])
    logger.info("SNS Message: " +
                json.dumps(sns_msg_attr, separators=(',', ':')))

    if sns_msg_attr is None:
        logger.critical("Unable to get required attributes from SNS message!")
        utl.put_line_in_log('SNS Handler Finished', 'thin')
        return
    try:
        if sns_msg_attr['instance_id'] is None:
            logger.critical("Received instance_id None!")
            utl.put_line_in_log('SNS Handler Finished', 'thin')
            return
        if int(sns_msg_attr['counter']
               ) <= 0 and sns_msg_attr['to_function'] != 'vm_delete':
            message_subject = 'EVENT: ' + utl.e_var['AutoScaleGrpName'] + ' ' + 'instance delete' + ' ' + \
                              sns_msg_attr['instance_id']
            sns.publish_to_topic(utl.e_var['AutoScaleManagerTopic'],
                                 'VM not accessible', message_subject,
                                 'vm_delete', 'FIRST',
                                 sns_msg_attr['instance_id'])
            logger.critical("Has ran out of retries! calling vm_delete...")
            utl.put_line_in_log('SNS Handler Finished', 'thin')
            return
        elif int(sns_msg_attr['counter']
                 ) <= 0 and sns_msg_attr['to_function'] == 'vm_delete':
            logger.critical("Unable to delete device %s" %
                            sns_msg_attr['instance_id'])
            utl.put_line_in_log('SNS Handler Finished', 'thin')
            return
    except KeyError as e:
        logger.error(
            "Unable to get one of required parameter from SNS Message body: {}"
            .format(repr(e)))
        utl.put_line_in_log('SNS Handler Finished', 'thin')
        return

    # FMC class initialization
    fmc = FirepowerManagementCenter()
    fmc.get_auth_token()

    # FTD class initialization
    ftd = NgfwInstance(sns_msg_attr['instance_id'])
    instance_state = ftd.get_instance_state()
    logger.info("Instance %s " % sns_msg_attr['instance_id'] +
                "is in %s state" % instance_state)
    if sns_msg_attr['to_function'] == 'vm_delete':
        pass
    elif instance_state == 'running' or instance_state == 'pending':
        pass
    else:
        logger.error("Device in %s state, can't be handled by %s function" %
                     (instance_state, sns_msg_attr['to_function']))
        utl.put_line_in_log('SNS Handler Finished', 'thin')
        return

    logger.info("Continue to execute action of " + sns_msg_attr['to_function'])

    if sns_msg_attr['to_function'] == 'vm_ready':
        ftd.put_instance_name()
        if sns_msg_attr['category'] == 'FIRST':
            if execute_vm_ready_first(ftd) == 'SUCCESS':
                logger.info(
                    "SSH to NGFWv with instance_id is successful, Next action: Registration"
                )
                message_subject = 'EVENT: ' + utl.e_var['AutoScaleGrpName'] + ' ' + 'instance register' + ' ' + \
                                  sns_msg_attr['instance_id']
                sns.publish_to_topic(utl.e_var['AutoScaleManagerTopic'],
                                     'VM is ready', message_subject,
                                     'vm_register', 'FIRST',
                                     sns_msg_attr['instance_id'])
            else:
                logger.warn(
                    "SSH to NGFWv with instance_id: %s is un-successful, Retrying..."
                    % sns_msg_attr['instance_id'])
                message_subject = 'EVENT: ' + utl.e_var['AutoScaleGrpName'] + ' ' + 'instance poll' + ' ' + \
                                  sns_msg_attr['instance_id']
                sns.publish_to_topic(utl.e_var['AutoScaleManagerTopic'],
                                     'Check VM is ready', message_subject,
                                     'vm_ready', 'FIRST',
                                     sns_msg_attr['instance_id'],
                                     str(int(sns_msg_attr['counter']) - 1))

    elif sns_msg_attr['to_function'] == 'vm_register':
        if sns_msg_attr['category'] == 'FIRST':
            if execute_vm_register_first(ftd, fmc) == 'SUCCESS':
                logger.info(
                    "Instance is registered to FMC, Next action: Configuration"
                )
                message_subject = 'EVENT: ' + utl.e_var['AutoScaleGrpName'] + ' ' + 'instance configure' + ' ' + \
                                  sns_msg_attr['instance_id']
                sns.publish_to_topic(utl.e_var['AutoScaleManagerTopic'],
                                     'VM registered', message_subject,
                                     'vm_configure', 'FIRST',
                                     sns_msg_attr['instance_id'])
            else:
                logger.warn(
                    "Registration failed! trying again in next cycle...")
                message_subject = 'EVENT: ' + utl.e_var['AutoScaleGrpName'] + ' ' + 'instance register' + ' ' + \
                                  sns_msg_attr['instance_id']
                sns.publish_to_topic(utl.e_var['AutoScaleManagerTopic'],
                                     'VM not registered', message_subject,
                                     'vm_register', 'FIRST',
                                     sns_msg_attr['instance_id'],
                                     str(int(sns_msg_attr['counter']) - 1))

    elif sns_msg_attr['to_function'] == 'vm_configure':
        if sns_msg_attr['category'] == 'FIRST':
            if execute_vm_configure_first(ftd, fmc) == 'SUCCESS':
                logger.info(
                    "Instance is configured in FMC, Next action: Deployment")
                message_subject = 'EVENT: ' + utl.e_var['AutoScaleGrpName'] + ' ' + 'instance deploy' + ' ' + \
                                  sns_msg_attr['instance_id']
                sns.publish_to_topic(utl.e_var['AutoScaleManagerTopic'],
                                     'VM is configured', message_subject,
                                     'vm_deploy', 'FIRST',
                                     sns_msg_attr['instance_id'])
            else:
                logger.warn(
                    "Configuration failed! trying again in next cycle...")
                message_subject = 'EVENT: ' + utl.e_var['AutoScaleGrpName'] + ' ' + 'instance configure' + ' ' + \
                                  sns_msg_attr['instance_id']
                sns.publish_to_topic(utl.e_var['AutoScaleManagerTopic'],
                                     'VM not configured', message_subject,
                                     'vm_configure', 'FIRST',
                                     sns_msg_attr['instance_id'],
                                     str(int(sns_msg_attr['counter']) - 1))

    elif sns_msg_attr['to_function'] == 'vm_deploy':
        if sns_msg_attr['category'] == 'FIRST':
            if execute_vm_deploy_first(ftd, fmc) == 'SUCCESS':
                logger.info(
                    "Configuration is deployed, health status in TG needs to be checked"
                )
            else:
                logger.warn("Deployment failed! trying again in next cycle...")
                message_subject = 'EVENT: ' + utl.e_var['AutoScaleGrpName'] + ' ' + 'instance deploy' + ' ' + \
                                  sns_msg_attr['instance_id']
                sns.publish_to_topic(utl.e_var['AutoScaleManagerTopic'],
                                     'VM not deployed', message_subject,
                                     'vm_deploy', 'FIRST',
                                     sns_msg_attr['instance_id'],
                                     str(int(sns_msg_attr['counter']) - 1))

    elif sns_msg_attr['to_function'] == 'vm_delete':
        if sns_msg_attr['category'] == 'FIRST':
            if execute_vm_delete_first(ftd, fmc) == 'SUCCESS':
                logger.info("Instance has been deleted! ")
            else:
                logger.critical("Unable to delete instance!")
                message_subject = 'EVENT: ' + utl.e_var['AutoScaleGrpName'] + ' ' + 'instance delete' + ' ' + \
                                  sns_msg_attr['instance_id']
                sns.publish_to_topic(utl.e_var['AutoScaleManagerTopic'],
                                     'VM not deleted from ASG',
                                     message_subject, 'vm_delete', 'FIRST',
                                     sns_msg_attr['instance_id'],
                                     str(int(sns_msg_attr['counter']) - 1))

    utl.put_line_in_log('SNS Handler Finished', 'thin')
    return
Exemplo n.º 5
0
def handle_cron_event(event):
    """
    Purpose:    Handler for CloudWatch EC2 event
    Parameters:
    Returns:
    Raises:
    """
    # AutoScale Group class initialization
    asg = AutoScaleGroup(e_var['AutoScaleGrpName'])
    instances_list = asg.get_instance_list()
    if len(instances_list) <= 0:
        logger.info("No instance found in AWS AutoScale Group")
        logger.info(
            "Will DISABLE Cron job for AutoScale Manager Health Doctor, gets ENABLED if new instance launches"
        )
        # Initialize CloudWatchEvent class
        cw_event = CloudWatchEvent(e_var['A_CRON_JOB_NAME'])
        cw_event.stop_cron_job()
        return

    inform_user = False
    data = {"autoscale_group": e_var['AutoScaleGrpName']}
    if const.DISABLE_HEALTH_DOCTOR is True:
        logger.info("Health Doctor running is disabled, check constant.py")
        return

    try:
        l_kill_ftd, l_unhealthy_ip = execute_instance_tg_health_doctor()
        if l_kill_ftd != []:
            logger.debug("Not empty l_kill_ftd")
            inform_user = True
        item = {
            "health_doctor_data": {
                "unhealthy_ftdv_": l_kill_ftd,
                "unhealthy_ip": l_unhealthy_ip
            }
        }
    except Exception as e:
        logger.exception(e)
    else:
        data.update(item)

    try:
        # AutoScaleGroup
        aws_grp = aws_asg_cls_init()
        # Initialize DerivedFMC & AutoScaleGroup
        fmc = fmc_cls_init()
        status = fmc_configuration_validation(fmc, aws_grp)
        logger.info("Fmc validation status: " + status)
        if status == 'FAIL':
            inform_user = True
    except Exception as e:
        logger.exception(e)
    else:
        data.update({"fmc_config_validation": fmc.configuration})

    if inform_user:
        # SNS class initialization
        sns = SimpleNotificationService()
        # Email to user
        if e_var['USER_NOTIFY_TOPIC_ARN'] is not None:
            message_subject = 'Event: ' + e_var[
                'AutoScaleGrpName'] + ' Health Doctor Report'
            msg_body = json.dumps(data, separators=(',', ':'))
            sns.publish_to_topic(e_var['USER_NOTIFY_TOPIC_ARN'],
                                 message_subject, msg_body)
        # -------------
    logger.info(json.dumps(data, sort_keys=True, separators=(',', ':')))
    return
Exemplo n.º 6
0
def handle_ec2_launch_event(instance_id):
    """
    Purpose:    Handler for EC2 launch event
    Parameters: Instance Id
    Returns:
    Raises:
    """
    utl.put_line_in_log('EC2 Launch Handler', 'thin')
    # SNS class initialization
    sns = SimpleNotificationService()
    if instance_id is not None:
        logger.info("Received EC2 launch notification for instance-id: " +
                    str(instance_id))

        # Enable Health Doctor
        cw_event = CloudWatchEvent(e_var['A_CRON_JOB_NAME'])
        status = cw_event.cron_job_status()
        if status == 'DISABLED':
            cw_event.start_cron_job()
            logger.info("ENABLED CloudWatch Rule: " + cw_event.name)
        else:
            logger.info("CloudWatch Rule: " + cw_event.name +
                        " is already ENABLED")

        # Initialize DerivedFMC & AutoScaleGroup
        fmc = fmc_cls_init()
        # FTD class initialization
        instance = ftd_cls_init(instance_id, fmc)

        instance_state = instance.get_instance_state()
        interfaces_ip = instance.get_instance_interfaces_ip()
        if interfaces_ip is None:
            logger.warn("Unable to get IPs of the instance" + instance_id)
            message_subject = 'Event: ' + e_var[
                'AutoScaleGrpName'] + ' ' + 'instance poll' + ' ' + instance_id
            msg_body = utl.sns_msg_body_configure_ftdv_topic(
                'vm_ready', 'FIRST', instance_id)
            sns.publish_to_topic(e_var['AutoScaleManagerTopic'],
                                 message_subject, msg_body)
            utl.put_line_in_log('EC2 Launch Handler finished', 'thin')
            return

        if instance_state == 'running' or instance_state == 'pending':
            logger.info("Instance %s is in state: %s" %
                        (instance_id, instance_state))
            message_subject = 'Event: ' + e_var[
                'AutoScaleGrpName'] + ' ' + 'instance poll' + ' ' + instance_id
            msg_body = utl.sns_msg_body_configure_ftdv_topic(
                'vm_ready', 'FIRST', instance_id)
            sns.publish_to_topic(e_var['AutoScaleManagerTopic'],
                                 message_subject, msg_body)
        else:
            logger.warn("Instance %s is in state: %s" %
                        (instance_id, instance_state))

        if e_var['USER_NOTIFY_TOPIC_ARN'] is not None:
            # Email to user
            details_of_the_device = None
            message_subject = 'Event: ' + e_var['AutoScaleGrpName'] + ' ' + instance_id + ' ' + \
                              'instance is launched'
            msg_body = utl.sns_msg_body_user_notify_topic(
                'VM Launched', e_var['AutoScaleGrpName'], instance_id,
                details_of_the_device)
            sns.publish_to_topic(e_var['USER_NOTIFY_TOPIC_ARN'],
                                 message_subject, msg_body)
            # -------------
    else:
        logger.critical("Received instance_id None!")
    utl.put_line_in_log('EC2 Launch Handler finished', 'thin')
    return
Exemplo n.º 7
0
def handle_sns_event(sns_data):
    """
    Purpose:    Handler for SNS event
    Parameters: SNS data from Lambda handler
    Returns:
    Raises:
    """
    utl.put_line_in_log('SNS Handler', 'thin')
    logger.debug("SNS Message: " + json.dumps(sns_data, separators=(',', ':')))

    # SNS class initialization
    sns = SimpleNotificationService()

    _m_attr = json.loads(sns_data['Message'])
    logger.info("SNS Message: " + json.dumps(_m_attr, separators=(',', ':')))

    if _m_attr is None:
        logger.critical("Unable to get required attributes from SNS message!")
        utl.put_line_in_log('SNS Handler Finished', 'thin')
        return

    if _m_attr['instance_id'] is None:
        logger.critical("Received instance_id None!")
        utl.put_line_in_log('SNS Handler Finished', 'thin')
        return

    # AutoScaleGroup
    aws_grp = aws_asg_cls_init()
    # Initialize DerivedFMC
    fmc = fmc_cls_init()
    # FTD class initialization
    ftd = ftd_cls_init(_m_attr['instance_id'], fmc)

    try:
        if int(_m_attr['counter']
               ) <= 0 and _m_attr['to_function'] != 'vm_delete':
            logger.critical("Lambda has ran out of retries, calling vm_delete")
            # Email to user
            details_of_the_device = json.dumps(ftd.get_instance_tags())
            logger.info(details_of_the_device)
            if e_var['USER_NOTIFY_TOPIC_ARN'] is not None:

                message_subject = 'Event: ' + e_var['AutoScaleGrpName'] + ' ' + \
                                  _m_attr['instance_id'] + ' ' + 'unable to complete ' + \
                                  _m_attr['to_function']
                msg_body = utl.sns_msg_body_user_notify_topic(
                    'VM not completing ' + _m_attr['to_function'],
                    e_var['AutoScaleGrpName'], _m_attr['instance_id'],
                    details_of_the_device)
                sns.publish_to_topic(e_var['USER_NOTIFY_TOPIC_ARN'],
                                     message_subject, msg_body)
            # -------------
            if not const.DISABLE_VM_DELETE_FUNC:
                message_subject = 'Event: ' + e_var['AutoScaleGrpName'] + ' ' + 'instance delete' + ' ' + \
                                  _m_attr['instance_id']
                msg_body = utl.sns_msg_body_configure_ftdv_topic(
                    'vm_delete', 'FIRST', _m_attr['instance_id'])
                sns.publish_to_topic(e_var['AutoScaleManagerTopic'],
                                     message_subject, msg_body)
            else:
                logger.info(
                    " vm_delete function is disabled! Check constant.py")
            utl.put_line_in_log('SNS Handler Finished', 'thin')
            return

        elif int(_m_attr['counter']
                 ) <= 0 and _m_attr['to_function'] == 'vm_delete':
            logger.critical("Unable to delete device %s" %
                            _m_attr['instance_id'])
            # Email to user
            details_of_the_device = json.dumps(ftd.get_instance_tags())
            logger.info(details_of_the_device)
            if e_var['USER_NOTIFY_TOPIC_ARN'] is not None:

                message_subject = 'Event: ' + e_var['AutoScaleGrpName'] + ' ' + \
                                  _m_attr['instance_id'] + ' ' + 'instance not deleted'
                msg_body = utl.sns_msg_body_user_notify_topic(
                    'VM not getting deleted', e_var['AutoScaleGrpName'],
                    _m_attr['instance_id'], details_of_the_device)
                sns.publish_to_topic(e_var['USER_NOTIFY_TOPIC_ARN'],
                                     message_subject, msg_body)
            # -------------
            utl.put_line_in_log('SNS Handler Finished', 'thin')
            return
    except KeyError as e:
        logger.error(
            "Unable to get one of required parameter from SNS Message body: {}"
            .format(repr(e)))
        utl.put_line_in_log('SNS Handler Finished', 'thin')
        return

    if (_m_attr['to_function'] == 'vm_ready' and int(_m_attr['counter']) == const.TO_FUN_RETRY_COUNT[0]) or \
            (_m_attr['to_function'] == 'vm_register' and int(_m_attr['counter']) == const.TO_FUN_RETRY_COUNT[1]) or \
            (_m_attr['to_function'] == 'vm_configure' and int(_m_attr['counter']) == const.TO_FUN_RETRY_COUNT[2]) or \
            (_m_attr['to_function'] == 'vm_deploy' and int(_m_attr['counter']) == const.TO_FUN_RETRY_COUNT[3]):
        logger.info("Fmc validation: " +
                    fmc_configuration_validation(fmc, aws_grp))
        if fmc.configuration_status == 'UN-CONFIGURED':
            # Email to user
            details_of_the_device = json.dumps(ftd.get_instance_tags())
            logger.info(details_of_the_device)
            if e_var['USER_NOTIFY_TOPIC_ARN'] is not None:
                message_subject = 'Event: ' + e_var['AutoScaleGrpName'] + ' ' + \
                                  _m_attr['instance_id'] + ' ' + 'unable to connect Fmc ' + \
                                  _m_attr['to_function']
                msg_body = utl.sns_msg_body_user_notify_topic(
                    "Unable to connect Fmc", e_var['AutoScaleGrpName'],
                    _m_attr['instance_id'], details_of_the_device)
                sns.publish_to_topic(e_var['USER_NOTIFY_TOPIC_ARN'],
                                     message_subject, msg_body)
            # -------------
            if not const.DISABLE_VM_DELETE_FUNC:
                logger.info("Terminating instance")
                message_subject = 'Event: ' + e_var['AutoScaleGrpName'] + ' ' + 'instance delete' + ' ' + \
                                  _m_attr['instance_id']
                msg_body = utl.sns_msg_body_configure_ftdv_topic(
                    'vm_delete', 'FIRST', _m_attr['instance_id'])
                sns.publish_to_topic(e_var['AutoScaleManagerTopic'],
                                     message_subject, msg_body)
            else:
                logger.info(
                    "Need to terminate the instance, but vm_delete function is disabled, check constant.py"
                )
            return

    instance_state = ftd.get_instance_state()
    logger.info("Instance %s " % _m_attr['instance_id'] +
                "is in %s state" % instance_state)
    if _m_attr['to_function'] == 'vm_delete':
        pass
    elif instance_state == 'running' or instance_state == 'pending':
        pass
    else:
        logger.error("Device in %s state, can't be handled by %s function" %
                     (instance_state, _m_attr['to_function']))
        utl.put_line_in_log('SNS Handler Finished', 'thin')
        return

    logger.info("Continue to execute action of " + _m_attr['to_function'])

    if _m_attr['to_function'] == 'vm_ready':
        if const.DISABLE_VM_READY_FUNC is True:
            logger.info(_m_attr['to_function'] +
                        " function is disabled! Check constant.py")
            utl.put_line_in_log('SNS Handler Finished', 'thin')
            return
        ftd.create_instance_tags('Name',
                                 ftd.vm_name)  # To put Name tag on instance
        if _m_attr['category'] == 'FIRST':
            if execute_vm_ready_first(ftd) == 'SUCCESS':
                ftd.create_instance_tags('NGFWvConnectionStatus', 'AVAILABLE')
                logger.info(
                    "SSH to NGFWv with instance_id is successful, Next action: Registration"
                )
                if not const.DISABLE_VM_REGISTER_FUNC:
                    message_subject = 'Event: ' + e_var['AutoScaleGrpName'] + ' ' + 'instance register' + ' ' + \
                                      _m_attr['instance_id']
                    msg_body = utl.sns_msg_body_configure_ftdv_topic(
                        'vm_register', 'FIRST', _m_attr['instance_id'])
                    sns.publish_to_topic(e_var['AutoScaleManagerTopic'],
                                         message_subject, msg_body)
                else:
                    logger.info(
                        " vm_register function is disabled! Check constant.py")
            else:
                logger.warn(
                    "SSH to NGFWv with instance_id: %s is un-successful, Retrying..."
                    % _m_attr['instance_id'])
                message_subject = 'Event: ' + e_var['AutoScaleGrpName'] + ' ' + 'instance poll' + ' ' + \
                                  _m_attr['instance_id']
                msg_body = utl.sns_msg_body_configure_ftdv_topic(
                    'vm_ready', 'FIRST', _m_attr['instance_id'],
                    str(int(_m_attr['counter']) - 1))
                sns.publish_to_topic(e_var['AutoScaleManagerTopic'],
                                     message_subject, msg_body)

    elif _m_attr['to_function'] == 'vm_register':
        if _m_attr['category'] == 'FIRST':
            if execute_vm_register_first(ftd) == 'SUCCESS':
                ftd.create_instance_tags('NGFWvRegistrationStatus', 'DONE')
                logger.info(
                    "Instance is registered to FMC, Next action: Configuration"
                )
                if not const.DISABLE_VM_CONFIGURE_FUNC:
                    message_subject = 'Event: ' + e_var['AutoScaleGrpName'] + ' ' + 'instance configure' + ' ' + \
                                      _m_attr['instance_id']
                    msg_body = utl.sns_msg_body_configure_ftdv_topic(
                        'vm_configure', 'FIRST', _m_attr['instance_id'])
                    sns.publish_to_topic(e_var['AutoScaleManagerTopic'],
                                         message_subject, msg_body)
                else:
                    logger.info(
                        " vm_configure function is disabled! Check constant.py"
                    )
            else:
                logger.warn(
                    "Registration failed! trying again in next cycle...")
                message_subject = 'Event: ' + e_var['AutoScaleGrpName'] + ' ' + 'instance register' + ' ' + \
                                  _m_attr['instance_id']
                msg_body = utl.sns_msg_body_configure_ftdv_topic(
                    'vm_register', 'FIRST', _m_attr['instance_id'],
                    str(int(_m_attr['counter']) - 1))
                sns.publish_to_topic(e_var['AutoScaleManagerTopic'],
                                     message_subject, msg_body)

    elif _m_attr['to_function'] == 'vm_configure':
        if _m_attr['category'] == 'FIRST':
            if execute_vm_configure_first(ftd) == 'SUCCESS':
                ftd.create_instance_tags('NGFWvConfigurationStatus', 'DONE')
                logger.info(
                    "Instance is configured in FMC, Next action: Deployment")
                if not const.DISABLE_VM_DEPLOY_FUNC:
                    message_subject = 'Event: ' + e_var['AutoScaleGrpName'] + ' ' + 'instance deploy' + ' ' + \
                                      _m_attr['instance_id']
                    msg_body = utl.sns_msg_body_configure_ftdv_topic(
                        'vm_deploy', 'FIRST', _m_attr['instance_id'])
                    sns.publish_to_topic(e_var['AutoScaleManagerTopic'],
                                         message_subject, msg_body)
                else:
                    logger.info(
                        " vm_deploy function is disabled! Check constant.py")
            else:
                logger.warn(
                    "Configuration failed! trying again in next cycle...")
                message_subject = 'Event: ' + e_var['AutoScaleGrpName'] + ' ' + 'instance configure' + ' ' + \
                                  _m_attr['instance_id']
                msg_body = utl.sns_msg_body_configure_ftdv_topic(
                    'vm_configure', 'FIRST', _m_attr['instance_id'],
                    str(int(_m_attr['counter']) - 1))
                sns.publish_to_topic(e_var['AutoScaleManagerTopic'],
                                     message_subject, msg_body)

    elif _m_attr['to_function'] == 'vm_deploy':
        if _m_attr['category'] == 'FIRST':
            if execute_vm_deploy_first(ftd, fmc) == 'SUCCESS':
                ftd.create_instance_tags('NGFWvConfigDeployStatus', 'DONE')
                logger.info(
                    "Configuration is deployed, health status in TG needs to be checked"
                )
                details_of_the_device = json.dumps(ftd.get_instance_tags())
                logger.info(details_of_the_device)
                if e_var['USER_NOTIFY_TOPIC_ARN'] is not None:
                    # Email to user
                    message_subject = 'Event: ' + e_var['AutoScaleGrpName'] + ' ' + \
                                      _m_attr['instance_id'] + ' ' + 'instance deploy configuration successful'
                    msg_body = utl.sns_msg_body_user_notify_topic(
                        'VM Configuration Deployed', e_var['AutoScaleGrpName'],
                        _m_attr['instance_id'], details_of_the_device)
                    sns.publish_to_topic(e_var['USER_NOTIFY_TOPIC_ARN'],
                                         message_subject, msg_body)
                    # -------------
            else:
                logger.warn("Deployment failed! trying again in next cycle...")
                message_subject = 'Event: ' + e_var['AutoScaleGrpName'] + ' ' + 'instance deploy' + ' ' + \
                                  _m_attr['instance_id']
                msg_body = utl.sns_msg_body_configure_ftdv_topic(
                    'vm_deploy', 'FIRST', _m_attr['instance_id'],
                    str(int(_m_attr['counter']) - 1))
                sns.publish_to_topic(e_var['AutoScaleManagerTopic'],
                                     message_subject, msg_body)

    elif _m_attr['to_function'] == 'vm_delete':
        if _m_attr['category'] == 'FIRST':
            if execute_vm_delete_first(ftd, fmc) == 'SUCCESS':
                logger.info("Instance has been deleted")
            else:
                logger.critical("Unable to delete instance")
                message_subject = 'Event: ' + e_var['AutoScaleGrpName'] + ' ' + 'instance delete' + ' ' + \
                                  _m_attr['instance_id']
                msg_body = utl.sns_msg_body_configure_ftdv_topic(
                    'vm_delete', 'FIRST', _m_attr['instance_id'],
                    str(int(_m_attr['counter']) - 1))
                sns.publish_to_topic(e_var['AutoScaleManagerTopic'],
                                     message_subject, msg_body)

    utl.put_line_in_log('SNS Handler Finished', 'thin')
    return