def lambda_handler()

in infra/modules/lambda/ecs-scaledown-lambda/index.py [0:0]


def lambda_handler(event, context):

    line = event['Records'][0]['Sns']['Message']
    message = json.loads(line)
    Ec2InstanceId = message['EC2InstanceId']
    asgGroupName = message['AutoScalingGroupName']
    snsArn = event['Records'][0]['EventSubscriptionArn']
    TopicArn = event['Records'][0]['Sns']['TopicArn']

    lifecyclehookname = None
    clusterName = None
    tmpMsgAppend = None
    completeHook = 0

    logger.info("Lambda received the event %s",event)
    logger.debug("records: %s",event['Records'][0])
    logger.debug("sns: %s",event['Records'][0]['Sns'])
    logger.debug("Message: %s",message)
    logger.debug("Ec2 Instance Id %s ,%s",Ec2InstanceId, asgGroupName)
    logger.debug("SNS ARN %s",snsArn)

    # Describe instance attributes and get the Clustername from userdata section which would have set ECS_CLUSTER name
    ec2Resp = ec2Client.describe_instance_attribute(InstanceId=Ec2InstanceId, Attribute='userData')
    logger.debug("Describe instance attributes response %s",ec2Resp)
    userdataEncoded = ec2Resp['UserData']
    userdataDecoded = base64.b64decode(userdataEncoded['Value'])

    tmpList = userdataDecoded.split()
    for token in tmpList:
        if token.find("ECS_CLUSTER") > -1:
            # Split and get the cluster name
            clusterName = token.split('=')[1]
            logger.debug("Cluster name %s",clusterName)

    # Get list of container instance IDs from the clusterName
    clusterListResp = ecsClient.list_container_instances(cluster=clusterName)
    logger.debug("list container instances response %s",clusterListResp)

    # If the event received is instance terminating...
    if 'LifecycleTransition' in message.keys():
        logger.debug("message autoscaling %s",message['LifecycleTransition'])
        if message['LifecycleTransition'].find('autoscaling:EC2_INSTANCE_TERMINATING') > -1:

            # Get lifecycle hook name
            lifecycleHookName = message['LifecycleHookName']
            logger.debug("Setting lifecycle hook name %s ",lifecycleHookName)

            # Check if there are any tasks running on the instance
            tasksRunning, tmpMsgAppend = checkContainerInstanceTaskStatus(Ec2InstanceId)
            logger.debug("Returned values received: %s ",tasksRunning)
            if tmpMsgAppend != None:
                message.update(tmpMsgAppend)

            # If tasks are still running...
            if tasksRunning == 1:
                response = snsClient.list_subscriptions()
                for key in response['Subscriptions']:
                    logger.info("Endpoint %s AND TopicArn %s and protocol %s ",key['Endpoint'], key['TopicArn'],
                                                                                  key['Protocol'])
                    if TopicArn == key['TopicArn'] and key['Protocol'] == 'lambda':
                        logger.info("TopicArn match, publishToSNS function...")
                        msgResponse = publishToSNS(message, key['TopicArn'])
                        logger.debug("msgResponse %s and time is %s",msgResponse, datetime.datetime)
            # If tasks are NOT running...
            elif tasksRunning == 0:
                completeHook = 1
                logger.debug("Setting lifecycle to complete;No tasks are running on instance, completing lifecycle action....")

                try:
                    response = asgClient.complete_lifecycle_action(
                        LifecycleHookName=lifecycleHookName,
                        AutoScalingGroupName=asgGroupName,
                        LifecycleActionResult='CONTINUE',
                        InstanceId=Ec2InstanceId)
                    logger.info("Response received from complete_lifecycle_action %s",response)
                    logger.info("Completedlifecycle hook action")
                except Exception, e:
                    print(str(e))