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
- Go to the AWS SNS Console.
- Click the “Create Topic” button.
- Enter a name for your topic (e.g.,
IAMUserInactivityTopic
). - Click “Create topic.”
- Under “Subscriptions,” click “Create subscription.”
- Choose “Email” as the protocol.
- Enter the email address where you want to receive notifications.
- Click “Create subscription.”
- Confirm the subscription by clicking the link sent to your email.
Step 2: Open Lambda Console
- Go to the AWS Lambda Console.
- Click the “Create function” button.
Step 3: Configure Function
- Choose “Author from scratch.”
- Enter a name for your function (e.g.,
IAMUserInactivityFunction
). - Choose the runtime as
Python 3.10
.
Step 4: Execution Role
- 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”
- Click “Create Function” to proceed.
Step 6: Configure Trigger
- Scroll down to the “Add triggers” section.
- Click “Add trigger” and select “CloudWatch Events” from the list.
- 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
- Set the
number_of_days
(e.g. value, 90)andsns_topic_arn
are environment variables, you can add it in the "Environment variables" section.
Step 10: Save Changes:
- 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:
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!