• 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
EC2 Instance Resizing with AWS Lambda and Systems Manager

EC2 Instance Resizing with AWS Lambda and Systems Manager

Arya P B

  • 4 min read
EC2 Instance Resizing with AWS Lambda and Systems Manager

Generating audio, please wait...

In many AWS environments, the workload demands on EC2 instances can vary throughout the day. To optimize costs and performance, it’s often beneficial to dynamically adjust the instance type based on the workload. In this blog post, we’ll explore how to automate EC2 instance resizing using AWS Lambda and Systems Manager.

Prerequisites

Before we dive into the solution, make sure you have the following set up:

  1. AWS Account: Make sure you have an AWS account with the necessary permissions to create Lambda functions, EC2 instances, and Systems Manager documents.
  2. EC2 Instances with Tags: Identify the EC2 instances that you want to resize and ensure they are tagged appropriately. For example, tags like scale-up, scale-down, scale-up-time, and scale-down-time can be used. Note that the time values in the scale-up-time and scale-down-time tags must be in 24-hour format, and each time should be separated with '/'.

Architecture Overview

The solution uses AWS Lambda to trigger instance resizing based on the specified time. The Lambda function checks the current instance type and compares it with the scheduled scale-up and scale-down times. If a resize operation is required, it uses AWS Systems Manager (SSM) to start an automation document, which performs the instance resizing.

Screenshot from 2024-02-08 13-00-21.png

Implementation Steps:

1. Lambda Function Setup

Create a new Lambda function in the AWS Management Console with the following configuration:

  • Runtime: Python 3.10
  • Role: Create a new role with permissions for EC2 and SSM.
  • Triggers: Set up a CloudWatch Events trigger to schedule the Lambda function execution.

2. Lambda Function Code

Copy and paste the provided Python code into your Lambda function. This code uses the Boto3 library to interact with AWS services, including EC2 and SSM. It incorporates the AWS Systems Manager document with the name “AWS-ResizeInstance” to orchestrate the resizing process.

import boto3
from datetime import datetime, timedelta

ssm = boto3.client('ssm')
ec2 = boto3.client('ec2')

def get_instance_type(instance_id):
    response = ec2.describe_instances(InstanceIds=[instance_id])
    return response['Reservations'][0]['Instances'][0]['InstanceType'] if response['Reservations'] else None
def get_tags(response):
    for reservation in response['Reservations']:
        for instance in reservation['Instances']:
            tags = {tag['Key']: tag['Value'] for tag in instance.get('Tags', [])}
            return tags.get('scale-down'), tags.get('scale-up'), tags.get('scale-down-time'), tags.get('scale-up-time')
def resize_instance(instance_id, new_instance_type):
    try:
        ssm.start_automation_execution(
            DocumentName="AWS-ResizeInstance", 
            Parameters={'InstanceId': [instance_id], 'InstanceType': [new_instance_type]}
        )
        return f"Resizing {instance_id} to {new_instance_type} started."
    except Exception as e:
        return f"Error resizing instance: {str(e)}"

def find_times_within_30_minutes(time_list):
    current_time = datetime.now()

    for time_str in time_list:
        time = datetime.strptime(time_str, "%H:%M")
        thirty_minutes_ago = current_time - timedelta(minutes=30)

        if thirty_minutes_ago.time() <= time.time() <= current_time.time():
            return time.strftime("%H:%M")
    return None

# Lambda handler function
def lambda_handler(event, context):
    ec2 = boto3.client('ec2')
    instance_ids = [instance['InstanceId'] for reservation in ec2.describe_instances()['Reservations'] for instance in reservation['Instances']]

    for instance_id in instance_ids:
        current_instance_type = get_instance_type(instance_id)
        scale_down, scale_up, scale_down_time, scale_up_time = get_tags(ec2.describe_instances(InstanceIds=[instance_id]))

        if current_instance_type == scale_up and find_times_within_30_minutes(scale_down_time.split('/')):
            return resize_instance(instance_id, scale_down)
        
        elif current_instance_type == scale_down and find_times_within_30_minutes(scale_up_time.split('/')):
            return resize_instance(instance_id, scale_up)

3. EC2 Instance Tagging

Tag your EC2 instances with the following key-value pairs:

  • scale-up: The target instance type for scale-up.
  • scale-down: The target instance type for scale-down.
  • scale-up-time: The time window for scale-up operations (e.g., 17:51/01:10).
  • scale-down-time: The time window for scale-down operations (e.g., 17:00/02:30).

4. Testing

Test the Lambda function by manually triggering it and observing the logs. Ensure that the function correctly identifies the current instance type and performs the resizing operation within the specified time.

5. Scheduling

Set up a recurring CloudWatch Events rule to trigger the Lambda function at the desired intervals. For example, you might schedule it to run every hour. Configure the rule to trigger at regular intervals using a cron expression (e.g., cron(0 0 * * ? *) for daily execution).

AWS Systems Manager Document

The AWS Systems Manager document named “AWS-ResizeInstance” plays a crucial role in this solution. It orchestrates the resizing process by taking parameters InstanceId and InstanceType and executing the necessary steps to resize the specified EC2 instance.

Optimize your EC2 sizes effortlessly with this robust DevOps approach! Discover the simple Lambda + Systems Manager combo to auto-resize based on workload. Save costs, and boost performance. Read the guide & conquer operational complexity with ease!

  • DevOps
Promotional banner
Promotional banner

Analyzing AWS IAM Users: Access Key and Password Age

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

Analyzing AWS IAM Users: Access Key and Password Age

Analyzing AWS IAM Users: Access Key and Password Age
  • 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

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

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

Posts by Arya P B

Athena