AWS Lambda – reboot instance when HTTP unreachable for free

I was solving an issue that this server (micro instance in Amazon EC2) sometimes comes down and stop responding to HTTP requests and few more services stop working too but AWS healthchecks are still ok.

It does not happen very often so I have decided that I will reboot the machine when HTTP webpage stop containing some text using AWS Lambda.

Tutorial

IAM role

Firstly, we need to create IAM role for Lambda service. When creating Lambda service I automatically created a role with basic police and one additional –┬áReadOnly_and_EC2_basic.

After that I slightly modified role ReadOnly_and_EC2_basic and assigned RebootInstances policy to role.

After that I have created a new lambda function WebsiteCheck

Using Python 3.6

import json
from botocore.vendored import requests
import boto3
import time

# e.g. eu-west-1
region = 'xx-xxxx-x'
instances = ['x-xxxxxxxxxxx']
website = 'https://www.enigma14.eu/'
webstring = 'SearchText'

def lambda_handler(event, context):
    for i in range(0,3):
        if check_website():
            return 'Website OK'
        time.sleep(60)
    reboot_instance()
    return 'Restarted instances'
        
    
def check_website():
    r = requests.get(website)
    if webstring in r.text:
        return True
    else:
        return False

def reboot_instance():
    ec2 = boto3.client('ec2', region_name=region)
    ec2.reboot_instances(InstanceIds=instances)

I have also increased execution time to 10 minutes

Now in CloudWatch I have created a new rule WebsiteCheck

Which run lambda function every hour

Pricing

From pricing perspective, it usualy runs less than 1 seconds and uses around 30 MB of memory.

So if you look at AWS pricelist

You will see that you have 400,000 GB-seconds free, and you will use 30:1.000MB = 0,03 GB/s x 24 hours x 30 days = 21.6 GB/s so it will be completely free.

Enjoy!