• 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
Automating the scaling operations of Auto Scaling Groups (ASG) using AWS Lambda and the Boto3 SDK

Automating the scaling operations of Auto Scaling Groups (ASG) using AWS Lambda and the Boto3 SDK

Arya P B

  • 4 min read
Automating the scaling operations of Auto Scaling Groups (ASG) using AWS Lambda and the Boto3 SDK

Generating audio, please wait...

Auto Scaling Groups (ASGs) in AWS provide a powerful way to manage the scaling of your EC2 instances based on demand. This tutorial walks you through creating an AWS Lambda function in Python that updates ASGs based on specific tags set on the instances.

Prerequisites

  • AWS Lambda: Ensure you have permissions to manage Auto Scaling Groups (autoscaling:UpdateAutoScalingGroup, autoscaling:DescribeAutoScalingGroups).
  • IAM Role: Set up a Lambda execution role with necessary permissions to interact with EC2 and Auto Scaling.

The Lambda Function Code

Below is the Python script that will be deployed as an AWS 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):
"""
Update the Auto Scaling group with new scaling configurations.
"""
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):
"""
Extract specific tags from EC2 instances to determine the ASG behavior.
"""
stop_time = None
start_time = None
scheduled_action = None
manual_invocation = None
min_size = None
max_size = None
desired_capacity = None
# Parse relevant tags
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):
"""
Check and update Auto Scaling groups based on the provided tags and resource input.
"""
paginator = client.get_paginator('describe_auto_scaling_groups')
results = []
try:
# Paginate through ASG descriptions
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']
# Extract relevant tag values
manual_invocation, stop_time, start_time, scheduled_action, min_size, max_size, desired_capacity = get_tags_from_ec2(tags)
# Check if manual invocation is enabled
if manual_invocation == 'True':
if DesiredCapacity == 0:
if 'start' in resource:
# Start the ASG with specified sizes
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:
# Stop the ASG by setting all capacities to zero
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 no ASGs match the conditions
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):
"""
AWS Lambda entry point function.
"""
resource = event.get('input', '')
if 'asg' in resource:
return ec2(resource);

Code Explanation

  1. Updating Auto Scaling Groups:
  • The update_autoscaling_group function takes the Auto Scaling group name, minimum size, maximum size, and desired capacity, and updates the group accordingly.
  1. Extracting Tags from EC2:
  • The get_tags_from_ec2 function reads tags attached to the ASG to determine its behavior, such as manual invocation or scheduled actions.
  1. Managing ASGs Based on Resource Input:
  • The ec2 function fetches all Auto Scaling groups and checks if they meet specific tag criteria (manual-invocation). If the ASG is in a stopped state (DesiredCapacity == 0) and a "start" action is requested, the ASG is started with predefined sizes.
  • If the ASG is running and a “stop” action is requested, the ASG is stopped by setting capacities to zero.
  1. Lambda Handler:
  • The lambda_handler function is the entry point for the Lambda execution, triggering the ec2 function based on the resource input.

Deploying the Lambda Function

  1. Create a Lambda Function:
  • Go to the AWS Lambda Console and create a new function.
  • Copy and paste the above code into the function code editor.
  1. Set Up IAM Permissions:
  • Ensure your Lambda execution role has permissions for autoscaling:UpdateAutoScalingGroup and autoscaling:DescribeAutoScalingGroups.
  1. Test the Function:
  • Trigger the function with a sample event to verify the behavior.

Sample Input Event

Here’s an example of how you might structure an input event for testing:

{
"input": "asg-start"
}

or

{
"input": "asg-stop"
}

Conclusion

This Lambda function helps automate the management of Auto Scaling groups by reading specific tags and adjusting the group’s scaling properties. You can extend this setup to suit your specific needs by adding more conditions or actions based on other tags.

Implement this AWS Lambda function to automate your EC2 Auto Scaling Groups based on specific tags. Whether you need to start or stop your ASGs based on demand, this solution has you covered. Try it and ensure your resources are always optimized for performance and cost!

  • 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