• Skip to main content
  • Skip to primary sidebar
  • Skip to footer

securitywing

How to Schedule AWS EC2 Start and stop time using Lambda and Cloudwatch

by wing

To save your AWS cloud  operational cost, you can schedule EC2 instanes’ start and stop time using Lambda function.  When you define a lamda function, you need to setup a trigger, which specifies the event that can invoke the lambda fucntions. In this post, we will use the a specific UTC time as a trigger .  For example, you want to start EC2 instances at  06:30 UTC and want to stop the instanes at 20:30 UTC. 

EC2 Start schedule setup

Step 1: create a labmda function and specifiy  the EC2  instance IDs that you need to start. Paste the following code in the code editor.In this example, I have used python 2.7 and named the function  ‘server-start’.

import boto3

region = ‘eu-west-1’

instances = [‘i-0d9c727e8be4f6dfc’, ‘i-0e330be1705e29501’]

def lambda_handler(event, context):

    ec2 = boto3.client(‘ec2’, region_name=region)

    ec2.start_instances(InstanceIds=instances)

    print ‘started ec2 instances: ‘ + str(instances)

ec2 instance start with lambda function

Note: you need to create and assign a role to the lambda function to start and stop the instances(ec2:StartInstances,ec2:StopInstance). The easiest way to test the lambda function created above without creating custom role is to assign the AmazonEC2FullAccess permission to the function.

 

Step 2:  create a cloudwatch schedule event and point it to the Lambda function that you created in step 1 as shown below screenshot.

cloudwatch event to start ec2 instance

 

EC2 stop schedule setup

Step 1: You need to follow the similar steps that you used to schedule Ec2 instance. At first create a lambda function and name it (e.g server-stop) and then paste the following code. Remember to replace the instance IDs by your EC2 instance IDs.

import boto3

region = ‘eu-west-1’

instances = [‘i-0d9c727e8be4f6dfc’, ‘i-0e330be1705e29501’]

 

def lambda_handler(event, context):

    ec2 = boto3.client(‘ec2’, region_name=region)

    ec2.stop_instances(InstanceIds=instances)

    print ‘stopped ec2  instances: ‘ + str(instances)

lambda function to stop ec2 instance

Step 2: create a cloudwath event rule and select the serve-stop lamba as target as shown below screenshot.

ec2 stop event rule setup in cloudwatch

 

Scale down EC2 instances in a auto scaling group using Lambda function

To scale down the nunber of EC2 instances running under a auto scaling group at a particular time each day, you can create a lambda function and schedule the task inside the lambda as shown below:

import boto3
import datetime
client = boto3.client(‘autoscaling’)

def lambda_handler(event, context):
# TODO implement
response = client.put_scheduled_update_group_action(
AutoScalingGroupName=’WP-Auto-Scaling-Group’,
ScheduledActionName=’Scale-Down’,
Recurrence=’30 20 * * *’,
MinSize=1,
MaxSize=1,
DesiredCapacity=1
)

RDS instance start and stop with Lambda

To stop RDS instance use the following Lamba funciton.Remeber to replace ‘wp’ and ‘search’ by your own RDS instance id.

import boto3
region = ‘eu-west-1’

def lambda_handler(event, context):
      rds = boto3.client(‘rds’, region_name=region)
      myID= [‘wp’,’search’]
      for id in myID:
          rds.stop_db_instance(
         DBInstanceIdentifier= id
          )

To start RDS instance, use the Lambda code below:

import boto3
region = ‘eu-west-1’

def lambda_handler(event, context):
            rds = boto3.client(‘rds’, region_name=region)
            myID= [‘wp’,’search’]
            for id in myID:
                        rds.start_db_instance(
                        DBInstanceIdentifier= id
                        )

Related posts:

  1. 32 Effective Home Security Checklist
  2. How to Extend Linux LVM by Adding a New Hard Disk
  3. How to Setup AWS CloudFront for Externally Registered Domain Name
  4. What Elon Musk Needs Doing to Make X.com(Twitter) Great Again?

Filed Under: Off Track

Primary Sidebar

Please help us sharing

Categories

  • AWS
  • Basics
  • Containers
  • Cryptocurrency
  • Cyber
  • Internet Security and Safety
  • IS Audit
  • IT Security Exams
  • Law & Human Rights
  • Network Security Tips
  • Off Track
  • Social Media Governance
  • Tech Comparisons
  • Tech Stack Suitability
  • Telecom
  • Tutorial

CISSP Sample Test

Take a CISSP Sample Test

CISA Sample Test

CISA IT governance Sample test

Please Follow Us

Contact us for Ads

Go to Contact Form

Search

Footer

Copyrights

Protected by Copyscape Duplicate Content Detection Software

Securitywing.com reserves the copyrights of all of its published articles.No contents of this site is permitted to be published to anywhere else in the Internet.If any contents are found in any other websites, securitywing reserves the rights to file a DMCA complaint. But you have the right to use the link of any relevant article of this site to point from your website if you consider that it might improve the quality of your article.

Tags

audit AWS backup basics browser check cisco cloud computer configuration cyber data database email gmail hsrp ids iis informaiton internet kubernetes linux load balancing malware microsoft network protection redundancy risk router security security tips server social media SSL switch test tools vpn vrrp web webserver website windows wordpress

Copyright © 2010-2025 ·All Rights Reserved · SecurityWing.com