• 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

AWS Lambda for AMI and Snapshot Age Monitoring-Python

Arya P B

  • 3 min read
AWS Lambda for AMI and Snapshot Age Monitoring-Python

Generating audio, please wait...

Introduction

In this blog post, we’ll explore an AWS Lambda function designed to monitor the age of Amazon Machine Images (AMIs), EBS snapshots, and RDS snapshots in your AWS environment. This script checks for resources older than a specified threshold, providing insights into potential cleanup or rotation actions.

Prerequisites

Before we dive into the Lambda function, make sure you have the following:

  • AWS account with the necessary permissions to describe EC2 images, snapshots, and RDS snapshots.
  • AWS Lambda configured with an execution role that has permissions to interact with EC2 and RDS services.

The Lambda Function

import json
import boto3
from datetime import datetime, timedelta, timezone

import json
import os
import boto3
from datetime import datetime, timedelta, timezone

def lambda_handler(event, context):
Ami = []
Snapshot = []
n_days_threshold = int(os.environ['days'])

utc_timezone = timezone.utc

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

current_time = datetime.now(utc_timezone)

# Include EC2 AMIs
amis = ec2.describe_images(Owners=['self'])['Images']

for ami in amis:
creation_time = ami['CreationDate']
creation_datetime = datetime.strptime(creation_time, "%Y-%m-%dT%H:%M:%S.%fZ").replace(tzinfo=utc_timezone)
age = current_time - creation_datetime

if age.days > n_days_threshold:
print(f"EC2 AMI {ami['ImageId']} created more than {n_days_threshold} days ago.")
Ami.append({'ImageId': ami['ImageId']})

# Include EC2 snapshots
snapshots = ec2.describe_snapshots(OwnerIds=['self'])['Snapshots']

for snapshot in snapshots:
start_time = snapshot['StartTime'].astimezone(utc_timezone)
age = current_time - start_time

if age.days > n_days_threshold:
print(f"EC2 Snapshot ID: {snapshot['SnapshotId']} is older than {n_days_threshold} days.")
print(f"Snapshot Start Time: {start_time}")
Snapshot.append({'snapshot': snapshot['SnapshotId']})

# Include RDS snapshots
rds_snapshots = rds.describe_db_snapshots()['DBSnapshots']

for rds_snapshot in rds_snapshots:
snapshot_time = rds_snapshot['SnapshotCreateTime']
snapshot_datetime = snapshot_time.replace(tzinfo=utc_timezone)
age = current_time - snapshot_datetime

if age.days > n_days_threshold:
print(f"RDS Snapshot ID: {rds_snapshot['DBSnapshotIdentifier']} is older than {n_days_threshold} days.")
print(f"RDS Snapshot Create Time: {snapshot_datetime}")
Snapshot.append({'snapshot': rds_snapshot['DBSnapshotIdentifier']})

# Correct the message generation part
message = f"EC2 AMI {'/'.join(item['ImageId'] for item in Ami)} created more than {n_days_threshold} days ago.\n"
message += f"EC2 Snapshot ID: {'/'.join(item['snapshot'] for item in Snapshot)} is older than {n_days_threshold} days."

print(message)

# You can further modify the function based on your use case, e.g., sending notifications, deleting snapshots, etc.

return {
'statusCode': 200,
'body': json.dumps('Function executed successfully!')
}

How to Deploy and Test

Create a Lambda Function:

  • Open the AWS Lambda console.
  • Click “Create function.”
  • Choose “Author from scratch.”
  • Configure the basic settings and create a new execution role with EC2 and RDS permissions.

Copy and Paste Code:

  • In the Lambda function code editor, replace the existing code with the provided Python script.

Adjust Configurations:

  • Modify the n_days_threshold variable to set your desired threshold for resource age.

Test the Lambda Function:

  • Save the Lambda function.
  • Manually test the Lambda function to observe its output in the AWS CloudWatch Logs.

Conclusion

This AWS Lambda function provides a powerful solution for monitoring the age of AMIs, snapshots, and RDS snapshots in your AWS environment. By customizing the script based on your specific requirements and scheduling it to run periodically, you can ensure that outdated resources are regularly identified and cleaned up.

Feel free to integrate additional features or notifications to suit your needs. AWS Lambda offers a scalable solution for automating tasks and responding to events within your AWS environment.

Optimize your AWS costs! This Lambda function monitors AMIs, snapshots, and RDS snapshots, identifying potentially outdated resources. Schedule it to run regularly and automate cleanup, saving you storage costs.

  • 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
AWS Lambda for AMI and Snapshot Age Monitoring-Python

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