AWS IAM User Management: How to get User Information using Lambda and Amazon S3
Tags: aws, serverless, python, cloud
Published: 2023-11-07 23:00:22


**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.

```bash
# 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"
```

**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.

```bash
# 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
```

**Setting up the Lambda Function:**
To create a Lambda function from the AWS Management Console, check [here.](https://docs.aws.amazon.com/lambda/latest/dg/getting-started.html#getting-started-create-function)
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:**
```python
import boto3
import csv
import os

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

**Step 4: List IAM Users:**
```python
    # Retrieve the list of users
    response = iam_client.list_users()
    users = response['Users']
```

**Step 5: Create a CSV File:**
```python
    # Create a temporary CSV file in the /tmp directory
    csv_filename = '/tmp/user_list.csv'
    csv_fields = ['Username', 'UserId', 'CreateDate']
```

**Step 6: Write User Information to CSV:**
```python
    # 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')
            })
```

**Step 7: Upload CSV to S3:**
```python
    # 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)
```
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](https://github.com/ogasege/get-aws-iam-users/blob/main/get-aws-iam-users.py).

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](https://docs.aws.amazon.com/IAM/latest/APIReference/welcome.html).

**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.