Reach Us

CloudifyOps Mini-blog series: Automating EC2 Start and Stop using AWS Lambda

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.

Lambda Implementation with Python:

Tag your EC2 Instances:

Begin by implementing a tagging strategy for your EC2 instances. Tags act as metadata, providing context and categorization to instances.

Set Up IAM Role for Lambda:

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.

Lambda Function Implementation:

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

Setting Up Triggers:

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.

BENEFITS

Cost Savings:

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.

Resource Efficiency:

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.

Operational Excellence:

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.

Privacy Settings
We use cookies to enhance your experience while using our website. If you are using our Services via a browser you can restrict, block or remove cookies through your web browser settings. We also use content and scripts from third parties that may use tracking technologies. You can selectively provide your consent below to allow such third party embeds. For complete information about the cookies we use, data we collect and how we process them, please check our Privacy Policy
Youtube
Consent to display content from - Youtube
Vimeo
Consent to display content from - Vimeo
Google Maps
Consent to display content from - Google
Spotify
Consent to display content from - Spotify
Sound Cloud
Consent to display content from - Sound
Contact Us