×

Schedule Starting/Stopping of EC2 Instance: Using Lambda (Python 3.8), Cloudwatch Events, IAM

AWS Elastic Compute Services are best suited in deploying reliable, secure, customizable, low-cost servers in comparison to the on-premises ones. The EC2 services provide secure, resizable, and flexible compute capacity in the cloud which is time as well as cost-effective.

Schedule Starting/Stopping of EC2 Instance: Using Lambda (Python 3.8), Cloudwatch Events, IAM

AWS Elastic Compute Services help you to deploy reliable, secure, customizable, low-cost servers as compared to the on-premises ones. If the server administrators take advantage of all these features along with other features of EC2 (e.g. scaling up and down) in a proper way, then it may save a lot of time and cost to the company/client. In most cases cost increases due to the continuous running of servers overnight/outside business hours, resulting in paying off more than what you are consuming. But this would not be the case if you can follow the simple solutions of scheduling your EC2 instances to start and stop so that they only run when they are in use. We have mentioned one of the simplest solutions below:

AWS Services Used:

1. Lambda (Runtime: Python 3.8)

2. IAM (Identity and Access Management)

3. Cloudwatch Events

Pricing Guide of the AWS Services Used:

1. Lambda:

a. Request Price - $0.20 per 1M requests (e.g. 20 request will cost $0.00 (20x$0.00000002=$0.000004))

b. Duration - $0.0000166667 for every GB-second (GB-sec = Number of request x duration per request(convert from ms to sec) x Memory allocated(convert from MB to GB))

2. IAM: IAM is a feature of your AWS account offered at no additional charge. You will be charged only for use of other AWS services by the users or EC2/Lambda assigned with a role.

3. Cloudwatch Events: Only chargeable for Custom Events and Cross account Events. You can use Schedule to invoke Lambda as a target.

Configuration in AWS Console:

Step 1: Create an IAM Policy to Allow starting and stopping EC2 Instances (along with the permission of uploading logs to Cloudwatch)

{

    "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": "*"

        }

    ]

}

Step 2: Create an IAM Role for Lambda, attach the above policy with the role.

Step 3: Jump to the Lambda Console “https://console.aws.amazon.com/lambda/home”, create a function for stopping EC2,

Create Function -> Author from scratch -> provide a function name -> choose python 3.8 for Runtime

In the “Permission” section select “Use an existing role” and choose the respective role created for Lambda. Create the function.

Step 4: Go to the code editor and write the following code:

import boto3

region = ''instance_region’'

instances = [‘instance_ID', 'instance_ID']

ec2 = boto3.client('ec2', region_name=region)

def lambda_handler(event, context):

     ec2.stop_instances(InstanceIds=instances)

     print('stopped your instances: ' + str(instances))

Then save the changes

Step 5: Test the function and see whether the function is stopping the mentioned instance or not.

Step 6: Create another function for starting EC2, 

Create Function -> Author from scratch -> provide a function name -> choose python 3.8 for Runtime

In the permission section select “Use an existing role” and choose the respective role created   for Lambda. Create the function.

Step 7: Go to the code editor and write the following code:

import boto3

region = ''instance_region’'

instances = [‘instance_ID', 'instance_ID']

ec2 = boto3.client('ec2', region_name=region)

def lambda_handler(event, context):

     ec2.start_instances(InstanceIds=instances)

     print('started your instances: ' + str(instances))

Then save the changes

Step 8: Test the function and see whether the function is starting the mentioned instance or not.

Step 9: Jump to the Cloudwatch console “https://console.aws.amazon.com/cloudwatch/”, 

Create events for starting EC2 Instance 

Go to Events -> Rules -> Create rule -> Select “Schedule” -> Select “Cron Expression” -> put “30 10 ? * MON-FRI *”(This will start the EC2 at 10:30 GMT everyday except weekend) -> Add

the respective lambda function (for starting the EC2) as Target -> Configure details -> Provide name and description -> Status to be Enabled -> Create rule.

Step 10: Jump to the Cloudwatch console “https://console.aws.amazon.com/cloudwatch/”, 

Create events for stopping EC2 Instance

Go to Events -> Rules -> Create rule -> Select “Schedule” -> Select “Cron Expression” -> put “0 22 ? * MON-FRI *”(This will stop the EC2 at 22:00 GMT everyday except weekend) -> Add the respective lambda function (for stopping the EC2) as Target -> Configure details -> Provide name and description -> Status to be Enabled -> Create rule.

For a more robust solution of this automation, you may also use AWS Instance Scheduler which is an automated CloudFormation template that launches, configures and runs the AWS services using AWS best practices for security and availability. This template will deploy the entire configuration automatically with a high-end configuration than the above simple solution. The scheduling configuration can be managed through Instance Scheduler CLI (Command Line Interface).




Trendy