️🚧 👷 We are still revamping our digital home - Thank you for your understanding as we improve.

Control Auto Scaling Groups: Start and Stop with Lambda

  • October 8, 2024
  • 4 min read
Control Auto Scaling Groups: Start and Stop with Lambda

Managing Auto Scaling groups can be a tedious task, especially when you need to adjust the group’s size based on specific schedules or manual triggers. This blog will guide you through creating an AWS Lambda function to start and stop Auto Scaling groups using API Gateway routes.

Prerequisites

Before you start, ensure you have the following:

  1. An AWS account.
  2. Basic knowledge of AWS Lambda and API Gateway.
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "autoscaling:UpdateAutoScalingGroup",
                "autoscaling:DescribeAutoScalingGroups"
            ],
            "Resource": "*"
        }
    ]
}

Step 2: Create the Lambda Function

import boto3
from botocore.exceptions import ClientError

client = boto3.client('autoscaling')

def update_autoscaling_group(asg_name, min_size, max_size, desired_capacity):
    try:
        response = client.update_auto_scaling_group(
            AutoScalingGroupName=asg_name,
            DesiredCapacity=desired_capacity,
            MinSize=min_size,
            MaxSize=max_size
        )
        return f"Auto Scaling group '{asg_name}' updated successfully."
    except Exception as e:
        return f"Error updating Auto Scaling group '{asg_name}': {e}"

def get_tags_from_ec2(tags):
    stop_time = None
    start_time = None
    scheduled_action = None
    manual_invocation = None
    min_size = None
    max_size = None
    desired_capacity = None

    for tag in tags:
        if tag['Key'] == 'manual-invocation':
            manual_invocation = tag['Value']
        elif tag['Key'] == 'stop-time':
            stop_time = tag['Value']
        elif tag['Key'] == 'start-time':
            start_time = tag['Value']
        elif tag['Key'] == 'scheduled-action':
            scheduled_action = tag['Value']
        elif tag['Key'] == 'min-size':
            min_size = int(tag['Value'])
        elif tag['Key'] == 'max-size':
            max_size = int(tag['Value'])
        elif tag['Key'] == 'desired-capacity':
            desired_capacity = int(tag['Value'])
    
    return manual_invocation, stop_time, start_time, scheduled_action, min_size, max_size, desired_capacity

def ec2(resource):
    paginator = client.get_paginator('describe_auto_scaling_groups')
    results = []

    try:
        for page in paginator.paginate():
            for group in page['AutoScalingGroups']:
                group_name = group['AutoScalingGroupName']
                tags = group['Tags']
                MinSize = group['MinSize']
                MaxSize = group['MaxSize']
                DesiredCapacity = group['DesiredCapacity']

                manual_invocation, stop_time, start_time, scheduled_action, min_size, max_size, desired_capacity = get_tags_from_ec2(tags)

                if manual_invocation == 'True':
                    if DesiredCapacity == 0:
                        if 'start' in resource:
                            min_size = 1
                            max_size = 1
                            desired_capacity = 1
                            result = update_autoscaling_group(group_name, min_size, max_size, desired_capacity)
                            results.append(result)
                        else:
                            results.append(f"Autoscaling Group '{group_name}' already in stop state")
                    elif DesiredCapacity > 0:
                        if 'stop' in resource:
                            min_size = 0
                            max_size = 0
                            desired_capacity = 0
                            result = update_autoscaling_group(group_name, min_size, max_size, desired_capacity)
                            results.append(result)
                        else:
                            results.append(f"Autoscaling Group '{group_name}' already in start state")
                else:
                    results.append(f"Auto Scaling Group '{group_name}': manual invocation not set to True")
        
        if not results:
            return "No Auto Scaling Group with the specified tags found."

        return results
    except Exception as e:
        return f"Internal Server Error: {str(e)}"

def lambda_handler(event, context):
    resource = event.get('input', '')

    if 'asg' in resource:
       return ec2(resource)

Step 3: Deploy the Lambda Function

  1. Open the AWS Management Console.
  2. Navigate to the Lambda service.
  3. Click on “Create function” and choose “Author from scratch”.
  4. Enter a name for your function and select the execution role you created earlier.
  5. Copy and paste the above Python script into the function code editor.
  6. Click “Deploy”.
     

Step 4: Set Up API Gateway

  1. Open the API Gateway service in the AWS Management Console.
  2. Click on “Create API” and choose “HTTP API”.
  3. Add a new route for starting the Auto Scaling Group:
  • Resource path: /asg/start
  1. Add another route for stopping the Auto Scaling Group:
  • Resource path: /asg/stop
  1. For both routes, set the integration target to your Lambda function.

Step 5: Test Your API

You can now test your API using tools like Postman or curl. Send a POST request to /asg/start or /asg/stop with the necessary payload.

For example, to start the Auto Scaling Group, you can use the following curl command:
https://<your-api-id>.execute-api.<region>.amazonaws.com/asg/start

Conclusion

By following these steps, you have successfully automated the process of increasing and decreasing the size of Auto Scaling Groups using AWS Lambda and API Gateway. This setup ensures efficient management of ASGs, allowing you to control them programmatically based on your needs.

Empower your cloud management strategy by implementing this AWS Lambda solution to automate your Auto Scaling Groups. Follow the steps in this blog to efficiently start and stop your ASGs, ensuring optimal performance and resource utilization to your specific needs.

Looking AWS experts?

We are providing top the line custom AWS setup services


Copyright © 2008 - 2024 SupportSages Pvt Ltd. All Rights Reserved.