In the dynamic cloud computing landscape, effective management of your AWS resources is crucial to optimize costs, enhance security, and maintain operational efficiency. Amazon Elastic Compute Cloud (EC2) instances are at the core of your infrastructure, and ensuring that they are managed properly is essential.
AWS offers a serverless approach to automation with AWS Lambda. Lambda allows you to execute code in response to events, such as scheduled time-based events. By using AWS Lambda, you can automate the start and stop of EC2 instances based on a predefined schedule and specified tags. This blog discusses how you can do this in detail.
Begin by implementing a tagging strategy for your EC2 instances. Tags act as metadata, providing context and categorization to instances.
For your Lambda function to interact with other AWS services, you need to create an IAM role that grants the necessary permissions. Provide Lambda roles with access to EC2, Cloudwatch, and EventBridge to perform the required actions.
Now, we come to the Python code for our Lambda function. This code is designed to carry out the critical tasks of identifying instances for either starting or stopping, all driven by the ‘AutoStartStop’ tag, and then taking the necessary actions.
Below is the Python code to start the EC2 Instance with respect to the tag.
import boto3 import os def lambda_handler(event, context): # Initialize the EC2 client region = os.environ.get('REGION', 'us-east-2') ec2 = boto3.client('ec2', region_name=region) # Replace 'your-region' with your AWS region # Define the tag key and value for instances to stop tag_key = 'Start-automatically' tag_value = 'True' # Get a list of instances with the specified tag response = ec2.describe_instances(Filters=[ { 'Name': f'tag:{tag_key}', 'Values': [tag_value] } ]) # Extract instance IDs from the response instance_ids = [] for reservation in response['Reservations']: for instance in reservation['Instances']: instance_ids.append(instance['InstanceId']) # Start the instances if instance_ids: ec2.start_instances(InstanceIds=instance_ids) print(f'Start the following instances: {instance_ids}') else: print('No instances found with the specified tag.') return 'No instances found with the specified tag.' return { 'Instances started':instance_ids, 'Total Instances started':len(instance_ids) } # Lambda function execution completes here
Below is the Python code to stop the EC2 instance with respect to the tag.
import boto3 import os def lambda_handler(event, context): # Initialize the EC2 client region = os.environ.get('REGION', 'us-east-2') ec2 = boto3.client('ec2', region_name=region) # Replace 'your-region' with your AWS region # Define the tag key and value for instances to stop tag_key = 'Stop-automatically' tag_value = 'True' # Get a list of instances with the specified tag response = ec2.describe_instances(Filters=[ { 'Name': f'tag:{tag_key}', 'Values': [tag_value] } ]) # Extract instance IDs from the response instance_ids = [] for reservation in response['Reservations']: for instance in reservation['Instances']: instance_ids.append(instance['InstanceId']) # Stop the instances if instance_ids: ec2.stop_instances(InstanceIds=instance_ids) print(f'Stopping the following instances: {instance_ids}') else: print('No instances found with the specified tag.') return 'No instances found with the specified tag.' return { 'Instances stopped':instance_ids, 'Total Instances stopped':len(instance_ids) } # Lambda function execution completes here
Our Lambda function is ready. But for it to run automatically, we need to set up triggers. One common trigger is a scheduled event through CloudWatch Events. You can create a rule that defines when and how often the Lambda function should execute.
The CloudWatch Events trigger has been configured to execute a Lambda function on weekdays (Monday to Friday), at 10 AM, for starting the EC2 instances.
For stopping the EC2 instances, the CloudWatch Events trigger has been configured to execute a Lambda function on weekdays (Monday to Friday), at 5 PM.
Automated start and stop operations translate to smarter resource use, especially in a cloud environment where resources are billed based on usage. Instances become active only when needed and are shut down during non-working hours or when not in use. Think of it like turning off lights when you leave a room – you’re not wasting electricity. You avoid unnecessary costs and benefit from significant savings over time.
Instances are like engines that only run when there’s work to be done. During business hours, they’re active and ready, while during idle periods, they’re put to rest. This efficient use of resources optimizes your infrastructure’s performance and extends its lifespan.
Consider your morning routine: some tasks are repetitive. If you could automate those tasks, you’d have more time to focus on important things. Similarly, automating routine tasks like starting and stopping instances frees up your team’s time. Instead of manually handling instances, your team can concentrate on strategic initiatives, innovation, and making your cloud infrastructure more resilient and efficient.
Talk to us if you are looking for Cost Optimization solutions for your AWS cloud infrastructure. Write to us at sales@cloudifyops.com.
CloudifyOps Pvt Ltd, Ground Floor, Block C, DSR Techno Cube, Survey No.68, Varthur Rd, Thubarahalli, Bengaluru, Karnataka 560037
Indiqube Vantage, 3rd Phase, No.1, OMR Service Road, Santhosh Nagar, Kandhanchavadi, Perungudi, Chennai, Tamil Nadu 600096.
CloudifyOps Inc.,
200, Continental Dr Suite 401,
Newark, Delaware 19713,
United States of America
Copyright 2024 CloudifyOps. All Rights Reserved