BK cloud / systems Notes
EN
English ENDeutsch DEEspañol ES中文 ZHFrançais FRPortuguês (Brasil) PT-BR日本語 JAहिन्दी HINederlands NL
Let’s connect ↗
← Back to field notes

AWS: restart EC2 on failure

Archive note: This 2019 article contains historical guidance, including a Python version that is no longer supported.

This blog ran on an EC2 instance. To keep costs down, I did not use a load balancer; instead, I used an Auto Scaling group with a desired capacity of one instance. The database connection occasionally became unreliable, in which case the simplest automated remedy was to restart the instance. Without a load balancer, that was not entirely straightforward, so I documented the process here.

  • Create a Route 53 health check.
  • Select the resulting CloudWatch alarm and attach an SNS topic.
  • Configure the topic to send you an email and invoke a Lambda function.
  • Ensure that the Lambda function’s IAM role allows it to reboot the EC2 instance.

Here is the Lambda code I found online. At the time this article was written, it required Python 2.7 rather than Python 3.x.

import boto3

region = ‘us-west-1’

instances = [‘i-12345cb6de4f78g9h’, ‘i-08ce9b2d7eccf6d26’]

def lambda_handler(event, context):

    ec2 = boto3.client(‘ec2’, region_name=region)

    ec2.stop_instances(InstanceIds=instances)

    print ‘stopped your instances: ‘ + str(instances)