Automate the process of stopping EC2 instances for a specific duration and then automatically restarting them.

Automate the process of stopping EC2 instances for a specific duration and then automatically restarting them.

Effortlessly schedule EC2 instances: Stop, pause, and resume with ease.

Introduction

Managing EC2 instances can be a challenge, especially when we tend to run them continuously even when they are not actively being used. This practice often leads to unnecessary costs and can easily be overlooked. However, there is a simple solution to this problem: automating the start and stop process of EC2 instances. By implementing an automated scheduling system, you can easily control when your instances should be running and when they should be shut down.

While AWS offers a built-in solution called the "AWS Instance Scheduler," some users find it a bit complex to set up and configure. Thankfully, there are alternative methods available that are equally effective and easier to implement. These methods allow you to define specific schedules for starting and stopping your instances, ensuring they are only active when you need them.

By automating the start and stop process of your EC2 instances, you can significantly reduce your AWS costs without compromising productivity. This approach ensures that instances are only running during the times you and your team are available for work or other related activities. It's a straightforward solution that can help you save money without requiring constant manual oversight.

Remember, implementing automated scheduling for EC2 instances is an excellent way to optimize your AWS usage and reduce unnecessary expenses.

Architecture Diagram

In our solution, we leverage the power of EventBridge schedule events and Lambda functions to automate the start and stop process of our EC2 instances. By setting up a schedule using EventBridge, we can trigger a Lambda function at specific times, such as 9 am and 9 pm every day, except for Saturdays and Sundays.

When the scheduled time arrives, the Lambda function is triggered, and it takes care of starting or stopping the instances based on our predefined logic. For example, at 9 am, the Lambda function starts the instances, ensuring they are up and running when we need them. Similarly, at 9 pm, the Lambda function initiates the shutdown process, turning off the instances and saving costs during non-working hours.

By excluding Saturdays and Sundays from the schedule, we ensure that no instances are running during weekends when they are not required for work. This further reduces unnecessary costs, allowing us to optimize our AWS usage effectively.

Procedure

Step-1: Create a Lambda Function

To implement the solution, we will create a Lambda function using Python as the runtime. We need to ensure that the Lambda function has the necessary permissions to stop the EC2 servers.

Here's the Python code that needs to be added.

import boto3

def lambda_handler(event, context):

    def stop_start_instances(instance_ids):
        ec2 = boto3.resource('ec2')
        instances = ec2.instances.filter(InstanceIds=instance_ids)

        for instance in instances:
            if instance.state['Name'] == 'running':
                instance.stop()
                print(f"Instance {instance.id} has been stopped.")
            elif instance.state['Name'] == 'stopped':
                instance.start()
                print(f"Instance {instance.id} has been started.")
            else:
                print(f"Instance {instance.id} is in an intermediate state: {instance.state['Name']}. Unable to perform the desired action.")

    # Specify the instance IDs to check and perform actions on
    instance_ids = ['<INSTANCE_ID_1>','<INSTANCE_ID_2>']

    # Call the function to stop or start the instances based on their current state
    stop_start_instances(instance_ids)

Make sure to replace the <INSTANCE_IDS> placeholder with the actual instance IDs for which you want to implement the solution.

Step-2: Create EventBridge Schedule

To set up the EventBridge schedule, follow these steps:

  1. Open the EventBridge console and navigate to the "Schedule" section.

  2. Click on "Create Schedule" to start creating a new schedule.

  3. In the "Schedule Pattern" field, provide the desired cron job expression. For instance, if you want the Lambda function to trigger at 9 AM and 9 PM only on weekdays, you can use the cron expression "0 9,21 ? * 1-5 *".

  4. In the Target section, choose the lambda function that we have created in the previous step.

That's it!

Congratulations! You have completed the setup for automatically starting and stopping your EC2 instances. With this implementation, your instances will now start and stop according to the defined schedule, ensuring optimal usage and cost savings. Gone are the days of manually starting and stopping instances, which often led to oversight and unnecessary costs.

Now, your instances will start at the designated times, such as 9 am, ensuring they are ready for your work. Similarly, at 9 pm, they will automatically shut down, eliminating any idle usage and reducing expenses during non-working hours. Additionally, by excluding weekends from the schedule, you further optimize costs by preventing instances from running when they are not required.

This setup brings peace of mind, as you can focus on your work without worrying about manually managing the instances. Enjoy the convenience of a streamlined process that maximizes efficiency and cost-effectiveness.

Keep in mind that you can always adjust the schedule, add more instances, or make any necessary modifications to fit your specific requirements. Enjoy the benefits of automated instance management and the cost savings it brings to your AWS environment.

Authors

For further information or any inquiries, please feel free to reach out to us via:
~ Linkedin – sahith palika | LinkedIn , Jaya Sree Gundasu | LinkedIn
~ Email ID – ,