DEV Community

Cover image for AWS IAM User Management: How to get User Information using Lambda and Amazon S3

AWS IAM User Management: How to get User Information using Lambda and Amazon S3

Introduction:
Managing IAM users in AWS is a crucial aspect of security and access control. In this blog post, we will explore how to use AWS Lambda, Boto3 (AWS SDK for Python), and S3 to automate the extraction of IAM user information and store it in a CSV file on Amazon S3. This solution is not only convenient but also serves as a valuable audit trail for IAM user management.

Prerequisites:

  1. AWS account with the necessary IAM permissions.
  2. Basic knowledge of AWS Lambda, IAM, and S3.

Setting up the AWS Environment:

Step 1: Create an S3 Bucket:
To run the code block below, open your preferred terminal or command prompt, paste the code block, and press Enter. Ensure you have the AWS CLI installed and configured with the necessary credentials.

# Set your preferred S3 bucket name
s3_bucket='iam-users1234'

# Create the S3 bucket
aws s3api create-bucket \
  --bucket $s3_bucket \
  --region us-east-1  # Choose your desired region

# Add a bucket policy to allow the Lambda function to upload objects
bucket_policy='{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {
        "Service": "lambda.amazonaws.com"
      },
      "Action": "s3:PutObject",
      "Resource": "arn:aws:s3:::'$s3_bucket'/*"
    }
  ]
}'
aws s3api put-bucket-policy \
  --bucket $s3_bucket \
  --policy "$bucket_policy"
Enter fullscreen mode Exit fullscreen mode

Step 2: Create an IAM Role for Lambda:
To run the code block below, open your preferred terminal or command prompt, paste the code block, and press Enter. Ensure you have the AWS CLI installed and configured with the necessary credentials.

# Create a trust policy document for the IAM role
trust_policy='{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {
        "Service": "lambda.amazonaws.com"
      },
      "Action": "sts:AssumeRole"
    }
  ]
}'

# Create the IAM role for Lambda
role_name='IAMUserExtractorRole'
aws iam create-role \
  --role-name $role_name \
  --assume-role-policy-document "$trust_policy"

# Attach the AWSLambdaBasicExecutionRole policy to the IAM role
aws iam attach-role-policy \
  --policy-arn arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole \
  --role-name $role_name
Enter fullscreen mode Exit fullscreen mode

Setting up the Lambda Function:
To create a Lambda function from the AWS Management Console, check here.
Attach the role created above with the necessary permissions to the Lambda function to enable Lambda to assume the role and perform the required actions.

After successfully creating the lambda function with a Python 3.11 runtime, copy the code blocks below and paste them into the function Code tab.

Step 3: IAM and S3 Clients Initialization:

import boto3
import csv
import os

def lambda_handler(event, context):
    # Initialize AWS clients
    iam_client = boto3.client('iam')
    s3_client = boto3.client('s3')
Enter fullscreen mode Exit fullscreen mode

Step 4: List IAM Users:

    # Retrieve the list of users
    response = iam_client.list_users()
    users = response['Users']
Enter fullscreen mode Exit fullscreen mode

Step 5: Create a CSV File:

    # Create a temporary CSV file in the /tmp directory
    csv_filename = '/tmp/user_list.csv'
    csv_fields = ['Username', 'UserId', 'CreateDate']
Enter fullscreen mode Exit fullscreen mode

Step 6: Write User Information to CSV:

    # Write user information to the CSV file
    with open(csv_filename, 'w', newline='') as csvfile:
        csv_writer = csv.DictWriter(csvfile, fieldnames=csv_fields)
        csv_writer.writeheader()

        for user in users:
            csv_writer.writerow({
                'Username': user['UserName'],
                'UserId': user['UserId'],
                'CreateDate': user['CreateDate'].strftime('%Y-%m-%d %H:%M:%S')
            })
Enter fullscreen mode Exit fullscreen mode

Step 7: Upload CSV to S3:

    # Set S3 bucket and key
    s3_bucket = 'iam-users1234'
    s3_key = 'user_list.csv'

    # Upload the CSV file to S3
    s3_client.upload_file(csv_filename, s3_bucket, s3_key)
Enter fullscreen mode Exit fullscreen mode

After copying these code blocks into the Code tab and replacing the S3 bucket name with the one you have created, deploy and test your function. If successful, a csv file named user_list.csv will be saved in the S3 bucket.

If you prefer to use the Python file directly, it can be found in the Github repository here.

It is important to note that several AWS IAM API actions can be performed to meet whatever your use case is. The comprehensive list of AWS IAM actions which are supported can be found here.

Conclusion:
By combining AWS Lambda, Boto3, and S3, a serverless solution to automate the extraction and storage of IAM user information has been created. This not only simplifies the process but also ensures that a historical record of user creation is maintained for compliance and auditing purposes. You can schedule this Lambda function to run at specific intervals, providing an up-to-date user listing in your S3 bucket. Automating IAM user management has never been more straightforward!

Thanks for making it this far! Kindly leave a comment and share.

Top comments (4)

Collapse
 
sajjadrahman56 profile image
Sajjad Rahman

sooner I will try this . Thank you

Collapse
 
cloudsege profile image
Oluwasegun Adedigba

You're welcome!

Collapse
 
pastajosh profile image
Olorunnifemi

Detailed read, would be hoping to use this in the nearest future on build on this myself, thank you

Collapse
 
cloudsege profile image
Oluwasegun Adedigba

Thanks! You're welcome!