def get_interruption_handling_properties()

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


def get_interruption_handling_properties(instance_id):
    # Describe tags for the instance that will be interrupted
    try:
        describe_tags_response = ec2client.describe_instances(InstanceIds=[instance_id])
        instance_tags = describe_tags_response['Reservations'][0]['Instances'][0]['Tags']
    except ClientError as e:
        error_message = "Unable to describe tags for instance id: {id}. ".format(id=instance_id) 
        logger.error( error_message + e.response['Error']['Message'])
        # Instance does not exist or cannot be described
        raise e

    interruption_handling_properties = {
        'controller-type': '',
        'controller-id': '',
        'managed': False }
    
    # Check if instance belongs to an ASG or to a Spot Fleet
    for tag in instance_tags:
        if tag['Key'] == 'aws:autoscaling:groupName':
            # Instance belongs to an Auto Scaling group
            interruption_handling_properties['controller-type'] = 'auto-scaling-group'
            interruption_handling_properties['controller-id'] = tag['Value']
        elif tag['Key'] == 'aws:ec2spot:fleet-request-id':
            # Instance belongs to a Spot Fleet
            interruption_handling_properties['controller-type'] = 'spot-fleet'
            interruption_handling_properties['controller-id'] = tag['Value']
        elif tag['Key'] == 'SpotInterruptionHandler/enabled':
            interruption_handling_properties['managed'] = tag['Value'].lower() == 'true'

    return interruption_handling_properties