Automatically stop EC2 instances over the weekend
Tags: ec2, aws, tutorial, cloud
Published: 2023-01-19 12:46:14

All of you would have come across this meme. It’s funny right but it is not so funny when it actually happens.

![meme](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4an4dbqg1e4nokh1im9l.png)

While working with EC2 instances, it happens that, we or anyone might forget to stop the EC2 instances which are not required to run over the weekends, and as a consequence, it adds up the cost. For example, if someone is working on a GPU instance (For ex: P3 family) and he or she forgets to stop that instance that is not required over the weekend, then the cost incurred by such an instance is quite high and unnecessary.

An automated process to stop & start the instances will help to avoid the scenario of needless billing and wastage of resources. As a part of the solution, we will leverage the Lambda function & EventBridge rule which will trigger the lambda function every `Friday at 8 PM IST` to stop all the instances & on `Monday at 8 AM IST` to start the instances.

_Note: The time mentioned to start & stop the instances is for the demo purpose and you can modify based on the requirement._

![Flow](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jysape6cs99rongc8qah.png)

As a part of the solution, the lambda function with necessary permissions will contain the logic to start & stop the instances across all regions. The EventBridge cron job rule will execute this lambda function based on the set time as a part of the rule via cron expression.

To deploy the above solution manually follow below steps

- Create the lambda function and write or upload the code. As a next step add the permissions to the IAM role of the lambda function to start, stop, describe the the EC2 instances
- Configure two EventBridge rules to trigger the lambda function twice a week. First rule to start instances and second to stop instances

To automate the solution deployment steps, we will use the CloudFormation template which you can download from the GitHub repository. For a high-level walk-through of the lambda function code & CloudFormation template, please refer the video mentioned at the end.

Goto CloudFormation service, upload the template & click next.

This template expects three inputs

- **CronJobStartSchedule**: Enter the cron expression that when you want to start all EC2 instances across all regions. The default value is `cron(30 2 ? * MON *)`. It represents, start the instances on Monday at 8 AM every week
- **CronJobStopSchedule**: Enter the cron expression that when you want to start all EC2 instances across all regions. The default value is `cron(30 14 ? * FRI *)`. It represents, stop the instances on Friday at 8 PM every week
- **InstanceIDs**: Suppose, certain instances should not be stopped and should be skipped from stopping. Hence, as a part of the input, enter the instance-ids in the list format to avoid them from stopping. This input will be set as the value of the environment variable `INSTANCE_IDS_TO_IGNORE_STOP` of the lambda function

![Stack details](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/g1v8itl8r01jz2fro8ev.png)

The cron job expression should be in the UTC timezone. If I want to run the cron job at `8:00 PM IST` then the UTC time will be `2:30 PM`. And as we know that Indian time zone is ahead by 5 & half hours, so if you add 5 hours and 30 mins to the `2:30 UTC` time zone, then it would be `8:00 PM IST`. And if you are in a different timezone then you need to do the conversion from your local timezone to UTC and then define the cron job expression accordingly.

![Cron expression example](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cec86mcbjepus6eczwtd.png)

`?` represents any day of the month
`*` means it includes all the values

To learn more about Cron Expressions , please refer to the [documentation](https://docs.aws.amazon.com/eventbridge/latest/userguide/eb-create-rule-schedule.html) 
**Cron expression syntax:** _cron(minutes hour day-of-month month day-of-week year)_

_If the requirement is just to stop the instances automatically and not to start automatically then please comment the last two blocks (1st block creates the EventBridge rule to start the instance & 2nd the block adds the permission) of the CloudFormation template_

After the stack details are configured, create the stack and it will create the defined resources. Post successful deployment of the solution, it will start and stop the instances across all regions based on the cron expression.

Apart from stopping the instance on Friday & starting the instances on Monday, you can also configure this cron expression to run daily to stop the instances which are not required to run overnight. So you can play around with this solution as per your needs.

If you like to follow along with me step by step then you can refer to this video.

{% embed https://youtu.be/YltVow5_pUs %}

If you have any questions, comments, or feedback then please leave them below. [Subscribe to my channel](https://www.youtube.com/srcecde?sub_confirmation=1) for more.