Automatically start a specific AWS EC2 Instance using EventBridge and Lambda


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
Open the IAM console
Navigate to Policies and click "Create policy"
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": "*" } ] }
Navigate to Roles and click "Create role"
Select "AWS service" as the trusted entity and choose "Lambda" as the use case
Select the custom policy that you have created in earlier step "DemoEC2StartStopPolicy"
Name the role "EC2AutoStartLambdaRole" and click Create
Step 2: Create the Lambda Function
Open the Lambda console
Click "Create function"
Choose "Author from scratch"
Set the following details:
Function name: EC2AutoStart
Runtime: Python 3.9
Execution role: Use the role created in Step 1
Click "Create function"
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))
- Click "Deploy" to save the function
Step 3: Create an EventBridge Rule
Open the Amazon EventBridge console
Click "Create rule"
Set a name for your rule "EC2AutoStartEventRule"
Provide a description for the rule "Start Protected EC2 Instances"
Event Bus as default
Rule Type Rule with an event pattern
Click Next
Select Event Source as AWS Events and EventBridge partner events
For the event pattern, choose "AWS services" as the source
Select "EC2" for the AWS service
Choose "EC2 Instance State-change Notification" for the event type
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
For the target, choose "Lambda function" and select the "EC2AutoStart" function created earlier
Click Next » Next » Create to finalize the rule
Step 4: Test the Setup
Stop the specified EC2 instance manually through the EC2 console
Wait a few moments for EventBridge to detect the state change event in the Event Bus and trigger the Lambda function.
Check the EC2 console to verify that the instance starts automatically
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)
Open the Rules page of the EventBridge console.
Select the rule(s) that you created.
Choose Delete.
Choose Delete.
To delete the Lambda function(s)
Open the Functions page of the Lambda console.
Select the function(s) that you created.
Choose Actions, Delete.
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!
Subscribe to my newsletter
Read articles from ferozekhan directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
