Automating EC2 Instance Start/Stop with AWS Lambda


Prerequisites
Before you begin, make sure you have:
An AWS account
At least one EC2 instance
Basic familiarity with AWS services like Lambda and EC2
Step 1: Tag Your EC2 Instances
To manage EC2 instances automatically, it's helpful to tag them. This makes it easier to filter which ones should be started or stopped.
Go to the EC2 Console
Select your instance
Click on the Tags tab
Add a new tag:
Key:
AutoSchedule
Value:
True
Step 2: Create an IAM Role for Lambda
Lambda needs permissions to manage EC2 instances. Letβs create a role for it:
Go to the IAM Console > Roles > Create Role
Choose AWS service > Lambda
Attach the following policies:
AmazonEC2FullAccess
(for demo purposes; use least privilege in production)
Name the role:
LambdaEC2SchedulerRole
Create the role
Step 3: Create the Lambda Function
Go to the Lambda Console
Click Create function
Choose:
Author from scratch
Function name:
EC2StartStopScheduler
Runtime: Python 3.9 (or latest)
Execution role: Use existing role > Select
LambdaEC2SchedulerRole
Add the following Python code:
import boto3 ec2 = boto3.client('ec2') TAG_KEY = 'AutoSchedule' TAG_VALUE = 'True' def lambda_handler(event, context): action = event.get('action') filters = [{ 'Name': f'tag:{TAG_KEY}', 'Values': [TAG_VALUE] }] instances = ec2.describe_instances(Filters=filters) instance_ids = [ instance['InstanceId'] for reservation in instances['Reservations'] for instance in reservation['Instances'] ] if not instance_ids: print("No instances found with the specified tag.") return if action == 'start': ec2.start_instances(InstanceIds=instance_ids) print(f"Started instances: {instance_ids}") elif action == 'stop': ec2.stop_instances(InstanceIds=instance_ids) print(f"Stopped instances: {instance_ids}") else: print("Invalid action. Use 'start' or 'stop'.")
Click Deploy
Step 4: Create CloudWatch Event Rules
To trigger the Lambda function on a schedule:
Go to CloudWatch > Rules > Create Rule
Choose Event Source:
Select Schedule
Use cron expression:
Start:
cron(0 9 * * ? *)
β every day at 9 AMStop:
cron(0 17 * * ? *)
β every day at 5 PM
Add a target:
Choose Lambda Function
Select
EC2StartStopScheduler
Configure input:
Choose Constant (JSON text)
For start rule:
{ "action": "start" }
For stop rule:
{ "action": "stop" }
Click Create
Repeat these steps to create both start and stop events.
Step 5: Test the Setup
You can test your Lambda function manually:
Go to the Lambda function
Click Test
Use test JSON:
{ "action": "start" }
Check if your EC2 instance starts. Then try with "action": "stop"
to stop it.
Results & Benefits
Once set up, your EC2 instances will automatically:
Start at 9 AM
Stop at 5 PM
Benefits:
πΈ Save Costs: Instances only run when needed
π Consistent Operations: Reduce human error
π Scalable: Apply to multiple instances with tags
Subscribe to my newsletter
Read articles from Durkesh blogs directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
