top of page
Writer's pictureKateryna

Save on AWS EC2 cost with Eventbridge and Lambda for Legacy Applications

Managing legacy applications in the cloud can be a costly endeavor, especially if you’re running EC2 instances continuously. While modern applications often scale dynamically, legacy applications tend to remain active 24/7, even during periods of low or no usage. This leads to unnecessary costs. However, AWS provides a solution: by leveraging Amazon EventBridge and AWS Lambda, you can schedule EC2 instance start and stop actions to optimize costs without impacting your application's availability.


In this blog, we’ll walk you through how to use EventBridge and Lambda to reduce costs while ensuring your legacy applications remain available when needed.


Why Automate EC2 Start and Stop Actions?


Many legacy applications don’t require constant uptime. For example, development, testing, or backup workloads often only run during business hours. By automating the start and stop times of EC2 instances, you can:


  • Reduce Costs: Only pay for compute resources during active hours.

  • Optimize Resources: Minimize waste by stopping unused instances.

  • Improve Efficiency: Simplify management with automated scheduling.


Solution Overview


AWS EventBridge allows you to create rules to trigger events based on schedules (e.g., CRON expressions). These rules can invoke AWS Lambda functions, which handle the logic for starting or stopping EC2 instances. This setup is particularly effective for legacy applications running on EC2 instances without built-in scaling capabilities.


Step-by-Step Implementation


1. Set Up an IAM Role


To interact with EC2 instances, the Lambda function needs permissions. Create an IAM role with the necessary policies:

  • Go to the IAM Console.

  • Create a new role with the AWS Lambda use case.

  • Attach the following policy:


{
    "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": "*"
        }
    ]
}
  • Save and note the role ARN.


2. Create Lambda Functions


Set up two Lambda functions: one to start instances and another to stop them.

  • Go to the AWS Lambda Console.

  • Create a new function.

  • Use the following Python code for starting instances:



import boto3
region = 'ca-central-1'
instances = ['i-XXXX']
ec2 = boto3.client('ec2', region_name=region)

def lambda_handler(event, context):
    ec2.start_instances(InstanceIds=instances)
    print('started skucaster instances: ' + str(instances))
  • For stopping instances, use:

import boto3
region = 'ca-central-1'
instances = ['i-XXXX']
ec2 = boto3.client('ec2', region_name=region)

def lambda_handler(event, context):
    ec2.stop_instances(InstanceIds=instances)
    print('stopped skucaster instances: ' + str(instances))
  • Assign the IAM role created earlier to both functions.


3. Set Up EventBridge Rules


  • Navigate to the EventBridge Console.

  • Create a new rule for starting instances:

  • Rule Type: Schedule

  • Schedule Expression: Use a CRON expression (e.g., 0 9 ? * to start at 9 AM UTC).

0 20 ? * FRI *
  • Target: Select the Lambda function for starting instances.

  • Create another rule for stopping instances:

    • Schedule Expression: Use a CRON expression (e.g., 0 18 ? * to stop at 6 PM UTC).

    • Target: Select the Lambda function for stopping instances.


Testing the Automation


  • Manually test the Lambda functions by invoking them in the Lambda console. Ensure the instances start and stop as expected.

  • Wait for the scheduled times defined in your EventBridge rules to verify automation.


Cost Savings in Action


By stopping instances during off-hours, you can save up to 70% on EC2 costs. For example:

  • A single m5.large instance costs approximately $0.096 per hour.

  • Running 24/7 costs $69 per month.

  • Running only 9 hours a day (business hours) reduces the cost to $26 per month—a 62% savings.


Best Practices


  • Tagging: Use tags like Environment=Development or Schedule=On to identify instances for automation. Modify Lambda functions to act only on tagged instances.

  • Error Handling: Add error handling in Lambda to manage edge cases, such as already-stopped instances.

  • Monitoring: Use AWS CloudWatch to monitor and log Lambda executions for auditing purposes.


Conclusion


By combining the scheduling power of EventBridge with the serverless flexibility of Lambda, you can efficiently manage legacy applications running on EC2 instances. This simple automation can lead to significant cost savings, allowing you to invest more in innovation rather than infrastructure.

Start implementing this cost-saving strategy today and make your legacy applications cloud-smart!

For a detailed guide, check out the official AWS documentation https://repost.aws/knowledge-center/start-stop-lambda-eventbridge

1 view0 comments

Contact Us

Thanks for submitting!

bottom of page