How to Start and Stop AWS EC2 Instances Automatically?
AWS EC2 instances

Introduction

It is difficult to start or stop instances manually on a daily basis. We create a Lambda function with the CloudWatch rule through which it automatically starts or stops the instance as per the predefined time in CloudWatch rule. It is also called the scheduler for AWS EC2 instance. There are some Benefits on using scheduler on EC2:

  • Access the instance as per the working hours.
  • Reduce costs.
  • Stop instance from loading up on weekends.
  • The time limit for employees for working on the instance.

Prerequisites

  • AWS account
  • IAM user in AWS account
  • IAM user must have permission to access services for creating Lambda function.
  • We need an IAM role to define what permissions our lambda function has.
  • CloudWatch permission to create Rules.

Steps to Start and Stop AWS EC2 instances Automatically

To Create IAM Role

Log in to the AWS console with root account or with IAM user who has permission to create Roles.

  • Click on Services and select IAM services.
  • IAM services page will open from the left panel click on Create Role.
  • Create Role page will open select lambda service(Because we need permission to access lambda function).
  • On selecting lambda function it will invite you to attach permission and policies to the role. but we will create our customer policy.

We want our function able to perform the following:

  • Read log for EC2.
  • Start EC2 instance
  • Stop EC2 instance

To create the above policy using a visual editor or by providing a JSON. You can use the below JSON policy.

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

Lambda function to start an EC2 instance

Navigate to the AWS Lambda Management Console from Services.

  • Click on Create function new page will open.
  • Select Author from Scratch.
  • Give a specific name for creating a lambda function in the Function name e.g.,StartEC2Instances.
  • Choose Python 3.7 as a runtime.
  • For roles select Use an existing role and select the role we made earlier.

Code

I m using Boto3. Boto3 is SDK for python, which provides programmatic connectivity to create, configure, and manage AWS services with python.

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))

Every time when the Lambda function will execute the instances are started (mention in the instance array).
​​​​​​​The lambda function to start the EC2 instance is completed. You can test it by clicking the Test button.

CloudWatch Rule to start EC2 Snapshot

The lambda function is created, and we use the CloudWatch rule to automate the lambda function.

  • Navigate to CloudWatch Management Console from Services.
  • From CloudWatch page move to Rules from left panel
  • Click on Create rule. A new page will open.
  • Use the below settings to create a rule.

The above settings to start an EC2 instance every day at 3:00 am (timezone GMT). You can use cron expression according to your requirement.

Targets are used to select the Lambda function for which the rule is used.

You can also use a Fixed rate of option to start EC2 instance if you want to start instance after a fixed number of minutes Hours and Days.

  • Back to the Lambda Management Console Function.
  • Select recently created function. The created lambda function page will open.
  • Click on Add trigger button from a Designer section.
  • Select the CloudWatch Events to trigger.
  • Use recently created CloudWatch rule from existing rules and click on Add.

Lambda function to stop an EC2 instance

  Navigate to the AWS Lambda Management Console from Services.

  • Click on Create function new page will open.
  • Select Author from Scratch.
  • Give a specific name for creating a lambda function in the Function name e.g.,StopEC2Instances.
  • Choose Python 3.7 as a runtime.
  • For roles select Use an existing role and select the role we made earlier.

Code

I m using Boto3. Boto3 is SDK for python, which provides programmatic connectivity to create, configure, and manage AWS services with python.

import boto3
region = 'us-west-1'
instances = ['i-0d2870e7767dc02ef']
ec2 = boto3.client('ec2', region_name=region)
​
def lambda_handler(event, context):
    ec2.stop_instances(InstanceIds=instances)
    print('stopped your instances: ' + str(instances))

Every time when the Lambda function will execute the instances are stopeed (mention in the instance array).
The lambda function to stop the EC2 instance is completed. You can test it by clicking the Test button.

    CloudWatch Rule to stop EC2 Snapshot

    The lambda function is created, and we use the CloudWatch rule to automate the lambda function.

    • Navigate to CloudWatch Management Console from Services.
    • From CloudWatch page move to Rules from left panel
    • Click on Create rule. A new page will open.
    • Use the below settings to create a rule.

    The above settings to stop an EC2 instance every day at 21:00 PM (timezone GMT). You can use cron expression according to your requirement.

    Targets are used to select the Lambda function for which the rule is used.

    You can also use a Fixed rate of option to start EC2 instance if you want to start instance after a fixed number of minutes Hours and Days.

    • Back to the Lambda Management Console Function.
    • Select recently created function. The created lambda function page will open.
    • Click on Add trigger button from a Designer section.
    • Select the CloudWatch Events to trigger.
    • Use recently created CloudWatch rule from existing rules and click on Add.

    Conclusion

    In this article, we have created a Lambda function to Start and Stop the EC2 instance using the CloudWatch Rule. The cron expression is used from the CloudWatch to run the Lambda function.

    Related Posts