AWS | How to start/stop Amazon EC2 server using Lambda Services

|
| By Webner

If you want to improve utilization of your Amazon EC2 machine instances by stopping and starting instances at specific time intervals then you have to use a CloudWatch Event to trigger a Lambda function to start and stop your EC2 instances at scheduled intervals. Cloud watch is used to schedule your jobs at specific time intervals (similar to cron job). There are different scenarios where you can use cloudwatch alarm. Suppose you want to trigger an alarm when CPU utilization goes beyond the threshold limit say CPU utilization goes above 90%. In the similar way, we can trigger Lambda services using cloudwatch to start & stop EC2 machine instances. You can use the below link for reference:

https://aws.amazon.com/premiumsupport/knowledge-center/start-stop-lambda-cloudwatch/

Below are the steps which will guide you to setup lambda services via cloudwatch:

1. Create a Lambda function with some informative/descriptive name:
1

2. Use below code to Turn on EC2-instance and replace the instances ID with actual one:

import boto3
# Enter the region your instances are in, e.g. 'us-east-1'
region = 'XX-XXXXX-X'
# Enter your instances here: ex. ['X-XXXXXXXX', 'X-XXXXXXXX']
instances = ['X-XXXXXXXX']
    def lambda_handler(event, context):
    ec2 = boto3.client('ec2', region_name=region)
    ec2.start_instances(InstanceIds=instances)
    print 'started your instances: ' + str(instances)

2

3. choose the below mentioned configurations:
3

4. To turn OFF EC2-machine and replace the instances ID with actual one:

import boto3
# Enter the region your instances are in, e.g. 'us-east-1'
region = 'XX-XXXXX-X'
# Enter your instances here: ex. ['X-XXXXXXXX', 'X-XXXXXXXX']
instances = ['X-XXXXXXXX']
 def lambda_handler(event, context):
    ec2 = boto3.client('ec2', region_name=region)
    ec2.stop_instances(Instance Ids=instances)
    print 'stopped your instances: ' + str(instances)

Repeat step 3 to use the same configurations.

5. Now open cloudwatch in new tab of browser and click Events and then click Create rule:
4

6. Here choose Schedule option and then you can define schedule time just like you do it in linux cron jobs:
5

Expression would in this format → * * * * ? *

7. choose Add target and then Lambda function to execute StartEc2Instances which created earlier in step 2 and also create new rule for StopEc2Instances:
6

After both rules created:
7

8. Now you have to add a trigger in Lambda function, click Add trigger
8

This will open in new tab
9

9. And now click on Blank square box and choose Cloudwatch Events – Schedule:
10

10. Now select the rule name and schedule expression from drop down menu and also put some description in box:
11

11. Triggers will list here and from here you can disable/enable or can delete EC2 instance:
12

Leave a Reply

Your email address will not be published. Required fields are marked *