AWS Lambda together with CloudWatch and SNS to restart Beanstalk app server as needed

Bruce Lu

February 10, 2020

Goal

Pre-reqs

Create SNS to receive log activities alarm notification

Create CloudWatch logging alarm based on log activities

Create Lambda to take action when no log activity reported by CloudWatch


import json
import boto3

ebc = boto3.client('elasticbeanstalk')

def handler_restart_app_server(event, context):
    response = ebc.restart_app_server(
      EnvironmentId='your-eb-env-id',
      EnvironmentName='your-eb-env-name'
    )
    print(response)
    
    return {
          'statusCode': 200,
          'body': json.dumps(response)
    }
  
def handler_request_log_100_lines(event, context):
    response = ebc.request_environment_info(
    EnvironmentName='your-env-name',
    #InfoType='tail'|'bundle'
    InfoType='tail'
    )
    print('---->')
    print(response)
    print('<----')
    return {
        'statusCode': 200,
        'body': json.dumps(response)
    }

def handler_describe_environment_health(event, context):
    response = ebc.describe_environment_health(
      EnvironmentId='your-env-Id',
      EnvironmentName='your-env-name',
      AttributeNames=[
       'Status',
     ])
    #print(response)
    return {
          "statusCode": 200,
          "body": json.dumps(response)
    }

Add Lambda Trigger

The purpose is to trigger our Lambda function whenever we got no log actitiy notification in our SNS topic

Testing

Just watch for the notification from our topic. Every time we get notification the Elastic Beanstalk app server would be restarted

Conclusion

We achived our goal to restart EB app server when no log activity reported by CloudWatch.