The Magic of Lambda: How I Made My EC2 Resize Itself

Опубликовано: 31 Октябрь 2024
на канале: cloud with mohsin
39
5

In today's tutorial, we are going to perform a demo of AWS Lambda function.

Please checkout my earlier video on deep dive of AWS Lambda function wherein we covered the following topics:

An Overview of Serverless Architecture
Monolithic vs Serverless Architecture
Serverless Secrets Revealed - AWS Lambda
Automatic scaling of AWS Lambda
Benefits
Use Cases
Key Limitations
Pricing

** Steps performed in today's session **
1. Launch an AWS ec2 instance with t2.micro instance type
2. Create a lambda function using author from scratch
3.Verify the IAM role created using the lambda function to allow AWS Cloudwatch logs and log streams
4. Test the "hello world" template using test event
5. Attach 'ec2fullpermission' policy to the IAM role as per step3.
6.Create a new event,upload the desired code and test the code to resize the ec2 instance from t2.micro to t2.medium. We have used
{"instanceId": "instance-ID"}
to for testing the new event
7. Verify the Cloudwatch logs

** python code used in the demo ***
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):
Retrieve the instance ID from the event parameter
instance_id = event['instanceId']

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.medium'})

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}'

I hope you will find this session interesting.

Please dont forget to like,share,comment and subscribe to my YouTube channel.

Feel free to write your comments below.

Happy Learning.

Take Care.