AWS Lambda — Automate Analyzing your Permissions using IAM Access Advisor

Copyright to AWS

As soon as I read about AWS IAM access advisor APIs, I knew this is something useful. Last week, we came across a use case where we wanted to get notified for all the IAM Roles with services, not accessed for more than 90 days.

⚡TL;DR

  • AWS Lambda — list IAM Roles with services, not accessed from more than 90 days.
  • AWS SES — get notified about all IAM Roles with the list of services not accessed for the last 90 days.

🔥But, how does It work?

We’ll go through creating an AWS Lambda to automate this task using access advisor APIs provided by Python Boto3. We’ll be using following access advisor APIs:

  • generate_service_last_accessed_details — generates the service last accessed data for an IAM resource (user, role, group, or policy). You need to call this API first to start a job that generates the service last accessed data for the IAM resource. This API returns a JobId that you will use for the other APIs, such as get_service_last_accessed_details, to determine the status of the job completion.
  • get_service_last_accessed_details — use this to retrieve the service last accessed data for an IAM resource based on the JobID you pass in.

Let’s get started with coding!

  1. Create Lambda, select Python 3.x run time and Attach IAM Role
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"ses:SendEmail",
"logs:CreateLogStream",
"ses:SendRawEmail",
"iam:GenerateServiceLastAccessedDetails",
"iam:ListRoles",
"iam:GetServiceLastAccessedDetails",
"logs:CreateLogGroup",
"logs:PutLogEvents"
],
"Resource": "*"
}
]
}

2. Get IAM Client to get service last accessed details:

def get_iam_client():
"""
Get identity and access management client
"""
return boto3.client('iam')

3. Get SES Client for sending email to notify:

def get_ses_client():
"""
Get simple email service client
"""
return boto3.client('ses')

4. Overall Lambda Function will look like this:

You’ll receive a clean email for all IAM roles like this:

Couple of things to note:

You can contact me via Email, Twitter and LinkedIn.