Stop/start EC2 instance on schedule basis to save cost

Tram Ho

Welcome to Day 13 of 100 Days of DevOps, Let’s continue this journey.

The simple goal is: save cost

Problem : Shutdown all EC2 versions in AWS Dev account at 6pm and open it again the next day at 9am (Monday to Friday). Actually this request still has a few of you.

Solution : You can use the Lambda function in combination with the CloudWatch Events to do this.

One of the big challenges in doing this is for developers who need to work late and he wants to run his instance past 6pm and have urgent patches working on weekends? A common solution I offer is to specify manual lists in Python Code (Lamda function).

Step 1 : We create the IAM Role so that Lambda can interact with the CloudWatch Event

Go to IAM Console https://console.aws.amazon.com/iam/home?region=us-west-2#/home -> Roles -> Create role

Next, select Create policy, IAM Policy will look like this

Step 2 : Create a Lambda function

  • Select Author from scratch
  • Name: Give your Lambda function any name
  • Runtime: Select Python2.7 as runtime
  • Role: Choose the role we create in first step
  • Click on Create function

In the next scenario we will create a function to stop / start instance

Stop instance code:

Note:

  • Change the Value of region
  • In the instance field specify instance id

Start instance code:

Step 3 : Create CloudWatch event to activate this Lambda function

  • Open the Amazon CloudWatch console.
  • Choose Events, and then choose Create rule.
  • Choose Schedule under Event Source.

The same goes for the Start instance

Note: here you adjust the crontab structure as you like (default according to UTC TimeZone)

Lambda function -> Monitoring -> View logs in CloudWatch

When the instance is stopped it is similar.

the start is the same.

So you have saved a lot of costs for your company already, then proposed that Tet bonus money for me =))

Good luck .

Reference: https://techzones.me/devops/stop-start-ec2-instance-on-schedule-basis-to-save-cost/

Share the news now

Source : Viblo