Automatically start a specific AWS EC2 Instance using EventBridge and Lambda

ferozekhanferozekhan
4 min read

In this guide, let me show you the process of setting up an automated system to start a specific EC2 instance whenever it enters a stopped state. We'll use Amazon EventBridge to monitor the instance state and trigger an AWS Lambda function written in Python 3.9 to start the instance.

Prerequisites:

  • An AWS account with appropriate permissions

  • A specific EC2 instance you want to monitor and automatically start

Step 1: Create an IAM Role for the Lambda Function

  1. Open the IAM console

  2. Navigate to Policies and click "Create policy"

  3. Create and Attach the following custom policy "DemoEC2StartStopPolicy"

     {
       "Version": "2012-10-17",
       "Statement": [
         {
           "Effect": "Allow",
           "Action": [
             "logs:CreateLogGroup",
             "logs:CreateLogStream",
             "logs:PutLogEvents"
           ],
           "Resource": "arn:aws:logs:*:*:*"
         },
         {
           "Effect": "Allow",
           "Action": [
             "ec2:Start*",
             "ec2:Stop*"
           ],
           "Resource": "*"
         }
       ]
     }
    
  4. Navigate to Roles and click "Create role"

  5. Select "AWS service" as the trusted entity and choose "Lambda" as the use case

  6. Select the custom policy that you have created in earlier step "DemoEC2StartStopPolicy"

  7. Name the role "EC2AutoStartLambdaRole" and click Create

Step 2: Create the Lambda Function

  1. Open the Lambda console

  2. Click "Create function"

  3. Choose "Author from scratch"

  4. Set the following details:

    • Function name: EC2AutoStart

    • Runtime: Python 3.9

    • Execution role: Use the role created in Step 1

  5. Click "Create function"

  6. Replace the default code with the following Python script:

import boto3
import os
import json

region = 'us-east-1'
ec2 = boto3.client('ec2', region_name=region)

def lambda_handler(event, context):
    print("Received event: " + json.dumps(event))
    instances=[ event['detail']['instance-id'] ]
    ec2.start_instances(InstanceIds=instances)
    print ('Protected instance stopped - starting up instance: '+str(instances))
  1. Click "Deploy" to save the function

Step 3: Create an EventBridge Rule

  1. Open the Amazon EventBridge console

  2. Click "Create rule"

  3. Set a name for your rule "EC2AutoStartEventRule"

  4. Provide a description for the rule "Start Protected EC2 Instances"

  5. Event Bus as default

  6. Rule Type Rule with an event pattern

  7. Click Next

  8. Select Event Source as AWS Events and EventBridge partner events

  9. For the event pattern, choose "AWS services" as the source

  10. Select "EC2" for the AWS service

  11. Choose "EC2 Instance State-change Notification" for the event type

  12. In the event pattern, specify the following:

    {
      "source": ["aws.ec2"],
      "detail-type": ["EC2 Instance State-change Notification"],
      "detail": {
        "state": ["stopped"],
        "instance-id": ["i-0448b38d895981dd0"]
      }
    }
    

    Replace 'i-0448b38d895981dd0' with your specific EC2 instance ID

  13. For the target, choose "Lambda function" and select the "EC2AutoStart" function created earlier

  14. Click Next » Next » Create to finalize the rule

Step 4: Test the Setup

  1. Stop the specified EC2 instance manually through the EC2 console

  2. Wait a few moments for EventBridge to detect the state change event in the Event Bus and trigger the Lambda function.

  3. Check the EC2 console to verify that the instance starts automatically

  4. Review the CloudWatch Logs for the Lambda function to see the execution details

Step 5: Cleanup your resources

You can now delete the resources that you created for this tutorial, unless you want to retain them. By deleting AWS resources that you are no longer using, you prevent unnecessary charges to your AWS account.

To delete the EventBridge rule(s)
  1. Open the Rules page of the EventBridge console.

  2. Select the rule(s) that you created.

  3. Choose Delete.

  4. Choose Delete.

To delete the Lambda function(s)
  1. Open the Functions page of the Lambda console.

  2. Select the function(s) that you created.

  3. Choose Actions, Delete.

  4. Choose Delete.

By following these steps, you've created an automated system that will start your specific EC2 instance whenever it enters a stopped state. This can be particularly useful for maintaining high availability of critical services or for quickly recovering from unexpected shutdowns.

Remember to test thoroughly in a non-production environment before implementing in your production setup, and always follow AWS best practices for security and cost management.

Kindly like and share with the community. Until next time, Cheers!

0
Subscribe to my newsletter

Read articles from ferozekhan directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

ferozekhan
ferozekhan