How do I stop and start Amazon EC2 instances at regular intervals using AWS Lambda automatically?

Use Case:

In this example, we use Lambda functions to start and stop EC2 instances, and then we use CloudWatch Events to start instances in the morning at 8:30AM and stop the instances in the night at 4:30PM.

Steps:

Login to AWS Console->Under Compute ->Click on Lambda and choose Create a Function.


Choose Author from scratch.

Enter a Name for your function, such as “StopEC2Instances”->From the Runtime drop-down menu, choose Python2.7->Expand the Role drop-down menu, and then choose Create a custom role. This opens a new tab or window in your browser.

In the IAM Role drop-down menu ->choose Create a new IAM Role, and enter a Role Name, such as “lambda_start_stop_ec2.”

 Expand View Policy Document, choose Edit, and then choose Ok when prompted to read the documentation. Edit the policy as follows:


{
  "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": "*"
    }
  ]
}

Choose Allow to complete the role and return to the AWS Lambda console, and then choose Create Function and you will get the below page.

Scroll down below to Function code and then modify the existing code to the code as shown below:

import boto3
# Enter the region your instances are in. Include only the region without specifying Availability Zone; e.g., 'us-east-1'
region = 'ap-south-1'
# Enter your instances here: ex. ['X-XXXXXXXX', 'X-XXXXXXXX']
instances = ['i-077b98fc54d6fcaea']

def lambda_handler(event, context):
ec2 = boto3.client('ec2', region_name=region)
ec2.stop_instances(InstanceIds=instances)
print 'stopped your instances: ' + str(instances)


 Scroll little further down >In Basic settings, enter 10 seconds for the function Timeout.->Choose Save.

Now we need to repeat these steps to create another function that starts your instances again by using the following steps.

Go to Lambda->Click on Create function.

Choose Author from scratch.

Enter a Name for your function, such as “StartEC2Instances.”->From the Runtime drop-down menu, choose Python2.7->Expand the Role drop-down menu, and then choose existing Role, and select “lambda_start_stop_ec2” role->Choose Create function.

Scroll down below to Function code and then modify the existing code to the code as shown below:

import boto3
# Enter the region your instances are in. Include only the region without specifying Availability Zone; e.g.; 'us-east-1'
region = 'ap-south-1'
# Enter your instances here: ex. ['X-XXXXXXXX', 'X-XXXXXXXX']
instances = ['i-077b98fc54d6fcaea']

def lambda_handler(event, context):
ec2 = boto3.client('ec2', region_name=region)
ec2.start_instances(InstanceIds=instances)
print 'started your instances: ' + str(instances)


 In Basic settings, enter 10 seconds for the function Timeout->Choose Save.

Test your functions

  Open the AWS Lambda Console and then choose Functions->Select Stop EC2 instances ->Go to Actions-> Click Test .

Configure test event page will appear-> In Event name, type a name, and then choose Create.

Choose Test to execute the function.

You will see the below screen with execution results as succeeded.This means your EC2 instance has been stopped.

Repeat same steps from step 19 to step 22 to start the EC2 instance.In Functions page ->Select Start EC2 instance->Go to Actions->Click Test ->Enter event name in the configure test event page and Click Create.

Choose Test to execute the function and you will see the below screen with execution results as succeeded.This means your EC2 instance has been started.

Create a CloudWatch Event that triggers your Lambda function to start your EC2 instance at 8:30AM in the morning and stop EC2 instance at 4:30PM in the evening.

Go to AWS CloudWatch Console->Choose Events and then choose Create rule.

Choose Schedule under Event Source->In the Cron expression,enter time interval.(By default time interval takes UTC timezone,so we have to vary according to our preferred timezone requirement.Here we are trying to stop EC2 instances from MON-FRI at 4:30PM automatically.)->Choose Add target, and then choose Lambda function->In Function->choose the Lambda function that stops your instances->Click Configure details.

For Name, type a meaningful name, such as “StopEC2Instances”->For Description, add a meaningful description, such as “stops EC2 instances every day at evening 4:30 PM IST -> For State, choose Enabled->Choose Create rule.

To start EC2 Instances ->Follow from step 25- step 27.Only change would be in the Cron Expression where we need to change time interval to start the EC2 instances.In the below screenshot,we will be starting EC2 instances daily at 8:30AM from MON-FRI.

Choose Add target, and then choose Lambda function->In Function->choose the Lambda function that starts your instances->Click Configure details.

For Name, type a meaningful name, such as “StartEC2Instances”->For Description, add a meaningful description, such as “start EC2 instances every day at morning 8:30 PM IST -> For State, choose Enabled->Choose Create rule.


0 views

©2019 by Raghavendra Kambhampati