• 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 IAM User Inactivity Notifications in AWS using Lambda, Python, and SNS

Arya P B

  • 3 min read
Automating IAM User Inactivity Notifications in AWS using Lambda, Python, and SNS

Generating audio, please wait...

In this tutorial, we’ll explore how to create an AWS Lambda function to identify IAM users who haven’t been active for a specified number of days and notify stakeholders through AWS Simple Notification Service (SNS). This serverless approach allows for efficient and scalable execution.

Prerequisites

Before getting started, make sure you have:

  • An AWS account with the necessary permissions to create Lambda functions, interact with IAM, and use SNS.
  • An email address where you want to receive notifications.

Creating the SNS Topic and Lambda Function

Step 1: Open SNS Console

  1. Go to the AWS SNS Console.
  2. Click the “Create Topic” button.
  3. Enter a name for your topic (e.g., IAMUserInactivityTopic).
  4. Click “Create topic.”
  5. Under “Subscriptions,” click “Create subscription.”
  6. Choose “Email” as the protocol.
  7. Enter the email address where you want to receive notifications.
  8. Click “Create subscription.”
  9. Confirm the subscription by clicking the link sent to your email.

Step 2: Open Lambda Console

  1. Go to the AWS Lambda Console.
  2. Click the “Create function” button.

Step 3: Configure Function

  1. Choose “Author from scratch.”
  2. Enter a name for your function (e.g., IAMUserInactivityFunction).
  3. Choose the runtime as Python 3.10.

Step 4: Execution Role

  1. Create a new role with basic Lambda permissions. Select “Create a new role with basic Lambda permissions” in the “Role” dropdown.

Step 5: Click “Create Function”

  1. Click “Create Function” to proceed.

Step 6: Configure Trigger

  1. Scroll down to the “Add triggers” section.
  2. Click “Add trigger” and select “CloudWatch Events” from the list.
  3. Configure the rule to trigger at regular intervals using a cron expression (e.g., cron(0 0 * * ? *) for daily execution).

Step 7: Write Lambda Function Code

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

def lambda_handler(event, context):
    number_of_days = os.environ['number_of_days']
    sns_topic_arn =os.environ['sns_topic_arn']
    number_of_days = int(number_of_days)
    n_days_ago = datetime.now(timezone.utc) - timedelta(days=number_of_days)
    iam = boto3.resource('iam')
    client = boto3.client('iam')
    
    users = []
    inactive_users = []
    
    response = client.list_users()
    for user_data in response['Users']:
        user_name = user_data['UserName']
        user = iam.User(user_name)
        users.append(user_name)
        
        # Check PasswordLastUsed
        password_last_used = user.password_last_used
        if password_last_used and password_last_used < n_days_ago:
            inactive_users.append(user_name)
        
        # Check access keys
        latest = user.password_last_used or user.create_date
        for k in user.access_keys.all():
            key_used = client.get_access_key_last_used(AccessKeyId=k.id) 
            
            # Check if 'LastUsedDate' is present in 'AccessKeyLastUsed'
            if 'LastUsedDate' in key_used.get('AccessKeyLastUsed', {}):
                key_date = key_used['AccessKeyLastUsed']['LastUsedDate']
                
                if key_date > latest and key_date < n_days_ago:
                    inactive_users.append(user_name)
    # Prepare the message for SNS
    message = f"IAM Users who have been inactive for more than {number_of_days} days: {', '.join(inactive_users)}"
    
    # Publish the message to SNS
    sns_client = boto3.client('sns')
    sns_client.publish(
        TopicArn=sns_topic_arn,
        Message=message,
        Subject=f"Inactive IAM Users Report ({number_of_days} days)"
    )

    return {
        'statusCode': 200,
        'body': json.dumps('Notification sent to SNS!')
    }

Step 9: Environment Variables

  1. Set the number_of_days (e.g. value, 90)and sns_topic_arnare environment variables, you can add it in the "Environment variables" section.

Step 10: Save Changes:

  1. Click “Save” at the top right of the page.

Result

After successful execution, you should receive a notification email with details about IAM users who haven’t been active for the specified number of days. Here’s an example of what the result email might look like:

Screenshot from 2024-02-07 23-32-37.png

By combining AWS Lambda, Python, SNS, and email subscriptions, you’ve created a scalable solution to identify inactive IAM users and notify stakeholders efficiently. The serverless approach ensures seamless integration into your AWS environment, providing timely notifications about user inactivity.

Ready to enhance your AWS security effortlessly? Dive into our step-by-step tutorial on creating a serverless AWS Lambda function to identify inactive IAM users. Explore how AWS SNS facilitates efficient notifications, allowing seamless integration with your AWS environment. Explore the tutorial now and take control of user inactivity!

  • DevOps
Promotional banner
Promotional banner
Automating IAM User Inactivity Notifications in AWS using Lambda, Python, and SNS

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