def handler()

in ec2-spot-interruption-handler/spot-interruption-handler/index.py [0:0]


def handler(event, context):
    
    # Get instance Id from event
    instance_id = event['detail']['instance-id']
    logger.info("Handling spot instance interruption notification for instance {id}".format(
        id=instance_id))
    
    interruption_handling_properties = get_interruption_handling_properties(instance_id)
    
    #if the instance is tagged as managed and belongs to an Auto Scaling group or a Spot Fleet
    if interruption_handling_properties['managed']:
        if interruption_handling_properties['controller-id'] != '':
            # if it's an Auto Scaling group call detachInstances
            if interruption_handling_properties['controller-type'] == 'auto-scaling-group':
                detach_instance_from_asg(instance_id, interruption_handling_properties['controller-id'])
                logger.info("INFO: Instance {id} has been successfully detached from {asg_name}".format(
                id=instance_id,asg_name=interruption_handling_properties['controller-id']))

            # If interruption commands have been set up for the Auto Scaling group or Spot Fleet, execute them
            if controller_has_defined_interruption_commands(interruption_handling_properties['controller-id']):
                run_commands_on_instance(instance_id, interruption_handling_properties['controller-id'])
            else:
                logging.info("No SSM Parameter with commands associated with {controller} group {id}".format(
                    controller=interruption_handling_properties['controller-type'], id=interruption_handling_properties['controller-id']))
        else:
            info_message = "No action taken. Instance {id} is not part of an Auto Scaling group or Spot Fleet.".format(
                id=instance_id)
            logger.info(info_message)
            return(info_message)
    else:
        info_message = "No action taken. Instance {id} is not managed by SpotInterruptionHandler.".format(
            id=instance_id)
        logger.info(info_message)
        return(info_message)
 
    info_message = "Interruption response actions completed for instance {id} belonging to {controller}".format(
        id=instance_id,controller=interruption_handling_properties['controller-id'])
    logger.info(info_message)
    return(info_message)