Sitemap

EC2 Start, Stop And Resizing By Using Lambda And Event Bridge

4 min readSep 5, 2024

--

Whether you want to start/stop EC2 instance with a time schedule,
Whether you want to manage instance size(values) by time schedule, you can use like this to reduce blah blah blah.

What is AWS Lambda?

AWS Lambda is a compute service that allows you to run code for virtually any type of application or serverless service without the need for server administration. AWS Lambda handles all the administrative tasks for you, including server and operating system maintenance, resource allocation, automatic scaling, code monitoring, and logging. All you need to do is provide your code in one of the languages supported by AWS Lambda.

What is AWS EventBridge?

AWS EventBridge is a powerful tool that enables you to build applications that react to state changes in real-time. It provides a flexible, scalable event bus service to connect your applications with data from AWS services, custom applications, and third-party SaaS applications. With EventBridge, you can set up event-driven architectures where events trigger actions, such as running a Lambda function or sending notifications.

Key Components of Event Bridge

  1. Event Bus: An event bus is a pipeline that receives events from different sources. You can have a default event bus and custom event buses.
  2. Event Source: This is where the events originate, such as AWS services, custom applications, or third-party services.
  3. Event Rule: Rules match incoming events and route them to target services like Lambda, SQS, SNS, and more.
  4. Event Target: The service or application that receives the event once it matches a rule.

###############################################################

Okay…let’s start for that topic !

  • Go to Lambda, then type function name.
Press enter or click to view image in full size

After that, choose python for Run time.

Press enter or click to view image in full size

Then, choose Create role. ( add EC2FullAccess and Event Bridge Schedular permission to that resulting role. ps: giving FullAccess is not best practice). After that, click to create.

Press enter or click to view image in full size

After that, enter the code to be deployed here. Then, click to deploy.(Code sample is added at the end of my blog).

Press enter or click to view image in full size

#####################

Get Soe Tint Aung’s stories in your inbox

Join Medium for free to get updates from this writer.

For Event Bridge, Go to Event Bridge and click to create rule.

Press enter or click to view image in full size

Enter name and choose schedule.

Press enter or click to view image in full size

Enter Schedule name.

Press enter or click to view image in full size
Press enter or click to view image in full size
Press enter or click to view image in full size
Press enter or click to view image in full size
Press enter or click to view image in full size
Press enter or click to view image in full size
Press enter or click to view image in full size

###############################################################

ec2_start.py

import boto3

Instance_ids = ['your instance id']

Region_Name = 'instance's region'

ec2 = boto3.client('ec2', region_name=Region_Name)
def lambda_handler(event, context):
ec2.start_instances(InstanceIds=Instance_ids)
print('Started: ' + str(Instance_idsnstances))

ec2_stop.py

import boto3

Instance_ids = ['your instance id']

Region_Name = 'instance's region'

ec2 = boto3.client('ec2', region_name=Region_Name)
def lambda_handler(event, context):
ec2.stop_instances(InstanceIds=Instance_ids)
print('stopped: ' + str(Instance_idsnstances))

EC2 Instance Type Resizing (eg: micro to medium)

medium_to_micro.py

import boto3
from botocore.exceptions import WaiterError

def wait_until_instance_stopped(ec2_client, instance_id):
waiter = ec2_client.get_waiter('instance_stopped')
try:
waiter.wait(InstanceIds=[instance_id])
except WaiterError as e:
# Handle the exception if the instance fails to stop within the specified timeout
print(f"Error waiting for instance to stop: {e}")

def lambda_handler(event, context):
# Type your instance-ID
instance_id = 'i-*******'

# Create an EC2 client
ec2_client = boto3.client('ec2')

try:
# Stop the instance
ec2_client.stop_instances(InstanceIds=[instance_id])

# Wait until the instance is stopped
wait_until_instance_stopped(ec2_client, instance_id)

# Modify the instance type
ec2_client.modify_instance_attribute(InstanceId=instance_id, InstanceType={'Value': 't2.micro'})

# Start the instance
ec2_client.start_instances(InstanceIds=[instance_id])

return 'Instance resizing complete.'

except Exception as e:
# Handle any exceptions that occur during the resizing process
return f'Error resizing instance: {e}'

--

--