• DevOps
    Case Study

    How we built a resilient multi-account, multi-cloud solution for a Health Tech service provider!

    READ CASESTUDY
    icon

    24/7 DevOps as a Service

    Round-the-clock DevOps for uninterrupted efficiency.

    icon

    Infrastructure as a Code

    Crafting infrastructure with ingenious code.

    icon

    CI/CD Pipeline

    Automated CI/CD pipeline for seamless deployments.

    icon

    DevSecOps

    Integrated security in continuous DevOps practices.

    icon

    Hire DevOps Engineers

    Level up your team with DevOps visionaries.

    icon

    Consulting Services

    Navigate success with expert DevOps consulting.

  • TechOps
    Case Study

    How we built a scalable Odoo solution for a Travel Tech service provider!

    READ CASESTUDY

    WEB HOSTING SUPPORT

    icon

    HelpDesk Support

    Highly skilled 24/7 HelpDesk Support

    icon

    Product Support

    Boost your product support with our expertise.

    MANAGED SERVICES

    icon

    Server Management

    Don’t let server issues slow you down. Let us manage them for you.

    icon

    Server Monitoring

    Safeguard your server health with our comprehensive monitoring solutions.

    STAFF AUGMENTATION

    icon

    Hire an Admin

    Transform your business operations with our expert administrative support.

    icon

    Hire a Team

    Augment your workforce with highly skilled professionals from our diverse talent pool.

  • CloudOps
    Case Study

    How we helped a Private Deemed University in India, save US $3500/m on hosting charges!

    READ CASESTUDY
    icon

    AWS Well Architected Review

    Round-the-clock for uninterrupted efficiency

    icon

    Optimize

    Efficient CloudOps mastery for seamless cloud management

    icon

    Manage

    Automated CI/CD pipeline for seamless deployments

    icon

    Migrate

    Upgrade the journey, Migrate & Modernize seamlessly

    icon

    Modernize

    Simplify compliance complexities with our dedicated services

    icon

    FinOps as a Service

    FinOps as a Service

  • SecOps
    Case Study

    How we built a scalable Odoo solution for TravelTech service provider!

    READ CASESTUDY
    icon

    VAPT

    Vulnerability Assessment and Penetration Testing

    icon

    Source Code Review

    Ensuring source code security ans safe practices to reduce risks

    icon

    Security Consultation

    On demand services for improving server security

    icon

    System Hardening

    Reduced vulnerability and proactive protection

    icon

    Managed SoC

    Monitors and maintains system security. Quick response on incidents.

    icon

    Compliance as a Service

    Regulatory compliance, reduced risk

  • Insights
    Case Study

    How we helped a Private Deemed University in India, save US $3,500/m on hosting charges!

    READ CASESTUDY
    icon

    Blog

    Explore our latest articles and insights

    icon

    Case Studies

    Read about our client success stories

    icon

    Flipbook

    Explore our latest Flipbook

    icon

    Events

    Join us at upcoming events and conferences

    icon

    Webinars

    Watch our educational webinar series

  • Our Story
  • Contact Us

Interested to collaborate?

Get in touch with us!

Ready to elevate your business with certified cloud expertise? Contact us today to learn how our team can help you leverage cloud technology to drive growth, streamline operations, and enhance security.

  • AWSAWS
  • Azure CloudAzure Cloud
  • Google CloudGoogle Cloud
  • Akamai CloudAkamai Cloud
  • OVHOVH
  • Digital OceanDigital Ocean
  • HetznerHetzner
  • Kubernetes Consultancy Services
  • K8s & Cloud native Solutions
  • 24/7 Infrastructure Monitoring
  • DevOps as a Service
  • Cloud CI/CD Solutions
  • White Labeled MSP Support
  • Our story
  • Life@SupportSages
  • Insights
  • Careers
  • Events
  • Contact Us

Connect with us!


LinkedInFacebookXInstagramYouTube

aws partneraws advanced partner
SupportSages

Copyright © 2008 – 2026 SupportSages Pvt Ltd. All Rights Reserved.
Privacy PolicyLegal TermsData ProtectionCookie Policy
Control Auto Scaling Groups: Start and Stop with Lambda

Control Auto Scaling Groups: Start and Stop with Lambda

Arya P B

  • 4 min read
Control Auto Scaling Groups: Start and Stop with Lambda

Generating audio, please wait...

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.

Step 1: Setting Up IAM Roles and Policies

{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"autoscaling:UpdateAutoScalingGroup",
"autoscaling:DescribeAutoScalingGroups"
],
"Resource": "*"
}
]
}

Step 2: Create the Lambda Function

Create a Lambda function using the following Python script. This script handles increasing and decreasing the size of Auto Scaling Groups based on tags and API Gateway routes.

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.

Unlock the full potential of your AWS infrastructure by implementing the strategies in this blog. Start automating your Auto Scaling Group management today!

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.

  • AWS
  • DevOps

Continue Your Journey With…

DevOps as a Service

DevOps as a Service

Let us do the heavy lifting for you

Promotional banner
Promotional banner

Analyzing AWS IAM Users: Access Key and Password Age

Analyzing AWS IAM Users: Access Key and Password Age
  • DevOps
logo

Analyzing AWS IAM Users: Access Key and Password Age

Analyzing AWS IAM Users: Access Key and Password Age
  • AWS
  • DevOps
logo

Auto-Restart EC2 Instances on Status Check Failure: Quick Setup Guide

Auto-Restart EC2 Instances on Status Check Failure: Quick Setup Guide
  • DevOps
logo

Auto-Restart EC2 Instances on Status Check Failure: Quick Setup Guide

Auto-Restart EC2 Instances on Status Check Failure: Quick Setup Guide
  • AWS
  • DevOps
logo

Posts by Arya P B

Athena