Going Serverless: Implementing an EC2 Scheduler with AWS Lambda

In this post, we'll explore how to create a serverless EC2 scheduler using AWS Lambda. This solution will help you automatically start and stop EC2 instances based on a predefined schedule, potentially saving significant costs on your AWS bill.

Why Use an EC2 Scheduler?

Many organizations have EC2 instances that don't need to run 24/7. For example, development or testing environments might only be needed during business hours. By automatically shutting down these instances when they're not in use, you can reduce your AWS costs significantly.

Components of Our Serverless EC2 Scheduler

  • AWS Lambda: To run our scheduling code without provisioning servers
  • Amazon EventBridge: To trigger our Lambda function on a schedule
  • IAM Role: To give Lambda permissions to start/stop EC2 instances
  • Python: Our programming language of choice for the Lambda function

Step 1: Create the Lambda Function

First, we'll create a Lambda function using Python. Here's a basic script to get you started:

import boto3

def lambda_handler(event, context):
    ec2 = boto3.client('ec2')
    
    # Get all EC2 instances
    instances = ec2.describe_instances()
    
    # Filter instances with the 'AutoOn' or 'AutoOff' tag
    for reservation in instances['Reservations']:
        for instance in reservation['Instances']:
            instance_id = instance['InstanceId']
            instance_state = instance['State']['Name']
            
            # Check for AutoOn tag
            if 'Tags' in instance:
                for tag in instance['Tags']:
                    if tag['Key'] == 'AutoOn' and event['action'] == 'start' and instance_state == 'stopped':
                        print(f"Starting instance {instance_id}")
                        ec2.start_instances(InstanceIds=[instance_id])
                    elif tag['Key'] == 'AutoOff' and event['action'] == 'stop' and instance_state == 'running':
                        print(f"Stopping instance {instance_id}")
                        ec2.stop_instances(InstanceIds=[instance_id])
    
    return {
        'statusCode': 200,
        'body': 'EC2 instances have been managed according to their tags'
    }

Step 2: Set Up IAM Role

Create an IAM role for your Lambda function with the following permissions:

  • ec2:DescribeInstances
  • ec2:StartInstances
  • ec2:StopInstances

Step 3: Create EventBridge Rules

Set up two EventBridge rules:

  1. One to start instances (e.g., Monday to Friday at 8 AM)
  2. Another to stop instances (e.g., Monday to Friday at 6 PM)

Each rule should trigger the Lambda function with the appropriate 'action' parameter ('start' or 'stop').

Step 4: Tag Your EC2 Instances

Add 'AutoOn' and 'AutoOff' tags to the EC2 instances you want to schedule. You can set the value to 'true' or leave it blank.

Conclusion

With this serverless EC2 scheduler in place, you can automatically manage your EC2 instances based on your desired schedule. This solution is scalable, cost-effective, and requires minimal maintenance. Remember to monitor your Lambda function executions and adjust the schedule as needed to optimize your AWS usage and costs.

Stay tuned for more AWS Lambda tutorials and best practices!