How to stop and start AWS EC2 instances at regular intervals using Lambda ?

How to stop and start AWS EC2 instances at regular intervals using Lambda ?

June 18, 2020 / Nirav Shah

AWS Lambda

  • As per AWS “AWS Lambda lets you run code without provisioning or managing servers. You pay only for the compute time you consume.
  • With Lambda, you can run code for virtually any type of application or backend service – all with zero administration. Just upload your code and Lambda takes care of everything required to run and scale your code with high availability. You can set up your code to automatically trigger from other AWS services or call it directly from any web or mobile app.

AWS EC2

  • As per AWS “Amazon Elastic Compute Cloud (Amazon EC2) is a web service that provides secure, resizable compute capacity in the cloud. It is designed to make web-scale cloud computing easier for developers.”
  • Amazon EC2’s simple web service interface allows you to obtain and configure capacity with minimal friction. It provides you with complete control of your computing resources and lets you run on Amazon’s proven computing environment.

Also read : Custom Cloud watch Metrics for AWS EC2 Instance

We will follow the steps as under

  1. Create a custom AWS Identity and Access Management (IAM) policy and execution role for your Lambda function.
  2. Create Lambda functions that stop and start your EC2 instances.
  3. Test your Lambda functions
  4. Create CloudWatch Events rules that trigger your function on a schedule. For example, you could create a rule to stop your EC2 instances at night, and another to start them again in the morning.

Pre-Requirements

Get the IDs of the EC2 instances that you want to stop and start, and then follow these instructions.

stop-start-AWS-EC2-instances-regular-intervals-using-Lambda

Steps To Start And Stop AWS EC2 Instance Using Lambda

1. Create a custom AWS Identity and Access Management (IAM) policy and execution role for your Lambda function.

Create an IAM policy using the JSON policy editor. Paste this JSON policy document into the policy editor:

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

2. Create Lambda functions that stop and start your EC2 instances.

Step 1

  • In the Lambda console, choose Create function.

stop-start-AWS-EC2-instances-regular-intervals-using-Lambda

Step 2

  • Choose Author from scratch.

stop-start-AWS-EC2-instances-regular-intervals-using-Lambda

Step 3

  • Under Basic information, add the following:

stop-start-AWS-EC2-instances-regular-intervals-using-Lambda

Step 4

  • For Function name, enter a name that identifies it as the function used to stop your EC2 instances. For example, “StopEC2Instances”.

stop-start-AWS-EC2-instances-regular-intervals-using-Lambda

Step 5

  • For Runtime, choose Python 3.7.

stop-start-AWS-EC2-instances-regular-intervals-using-Lambda

Step 6

  • Under Permissions, expand Choose or create an execution role.
  • Under Execution role, choose Use an existing role.
  • Under Existing role, choose the IAM role that you created.
  • Choose Create function.

stop-start-AWS-EC2-instances-regular-intervals-using-Lambda

Step 7

  • Copy this code, and then under Function code,This code stops the EC2 instances that you identify.
  • This Script is for stopping the server
import boto3
region = 'us-west-1'
instances = ['i-12345cb6de4f78g9h', 'i-08ce9b2d7eccf6d26']
ec2 = boto3.client('ec2', region_name=region)

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

Note: You have to create 2 different lambda function and do all the steps again just change the script in Step 7

  • Copy this code, and then under Function code,This code stops the EC2 instances that you identify.
  • This Script is for stopping the server
import boto3
region = 'us-west-1'
instances = ['i-12345cb6de4f78g9h', 'i-08ce9b2d7eccf6d26']
ec2 = boto3.client('ec2', region_name=region)


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

Note: For region, replace “us-west-1” with the AWS Region that your instances are in. For instances, replace the example EC2 instance IDs with the IDs of the specific instances that you want to stop and start.

stop-start-AWS-EC2-instances-regular-intervals-using-Lambda

Step 8

  • Under Basic settings, set Timeout to 10 seconds.

stop-start-AWS-EC2-instances-regular-intervals-using-Lambda

Note: Configure the Lambda function settings as needed for your use case. For example, if you want to stop and start multiple instances, you might need a different value for Timeout, as well as Memory.

Step 9

  • Choose Save.

stop-start-AWS-EC2-instances-regular-intervals-using-Lambda

3. Test your Lambda functions

Step 1

  • In the Lambda console, choose Functions.

Step 2

  • Select one of the functions that you created.

Step 3

  • Choose Actions, and then choose Test.

Step 4

  • In the Configure test event dialog, choose Create new test event.

Step 5

  • Enter an Event name, and then choose Create.

Note

You don’t need to change the JSON code for the test event—the function doesn’t use it.

Step 6

  • Choose Test to execute the function.

4. Create rules that trigger your Lambda functions

Step 1

  • Open the CloudWatch console.

Step 2

  • In the left navigation pane, under Events, choose Rules.

stop-start-AWS-EC2-instances-regular-intervals-using-Lambda

Step 3

  • Choose Create rule.

stop-start-AWS-EC2-instances-regular-intervals-using-Lambda

Step 4

  • Under Event Source, choose Schedule.

stop-start-AWS-EC2-instances-regular-intervals-using-Lambda

Step 5

  • Do either of the following:
  • For Fixed rate of, enter an interval of time in minutes, hours, or days.
  • stop-start-AWS-EC2-instances-regular-intervals-using-Lambda
  • For Cron expression, enter an expression that tells Lambda when to stop your instances.
  • stop-start-AWS-EC2-instances-regular-intervals-using-Lambda

Note

Cron expressions are evaluated in UTC. Be sure to adjust the expression for your preferred time zone.

Step 6

  • Under Targets, choose Add target.

stop-start-AWS-EC2-instances-regular-intervals-using-Lambda

Step 7

  • Choose Lambda function.

stop-start-AWS-EC2-instances-regular-intervals-using-Lambda

Step 8

  • For Function, choose the function that stops your EC2 instances.

stop-start-AWS-EC2-instances-regular-intervals-using-Lambda

Step 9

  • Choose Configure details.

stop-start-AWS-EC2-instances-regular-intervals-using-Lambda

Step 10

  • Under Rule definition, do the following:
  • For Name, enter a name to identify the rule, such as “StopEC2Instances”.
  • (Optional) For Description, describe your rule. For example, “Stops EC2 instances every night at 10 PM.”
  • For State, select the Enabled check box.

stop-start-AWS-EC2-instances-regular-intervals-using-Lambda

Step 11

  • Choose Create rule.

Once all these steps are successfully completed, you have your automated lambda function ready that will stop-start your specified instances at your specified time. If facing problems in implementation anywhere in this process, feel free to contact us and we will be more than happy to assist you.

Also read : Serverless compute on AWS: AWS Lambda

 

Talk to AWS Certified Consultant

    Spread Love By Sharing:

    Let’s Talk About Your Needed AWS Infrastructure Management Services

    Have queries about your project idea or concept? Please drop in your project details to discuss with our AWS Global Cloud Infrastructure service specialists and consultants.

    • Swift Hiring and Onboarding
    • Experienced and Trained AWS Team
    • Quality Consulting and Programming
    Let’s Connect and Discuss Your Project