Get Email Notification On AWS IAM User Creation

Example CloudWatch rule and Lambda function to send an email via SES whenever an IAM user is created

Vinayak Pandey

by Vinayak Pandey

Dec 16, 2021

0

In an Enterprise environment, keeping track of IAM users can be a tedious task. The recommended best practice is to integrate your company's Identity provider such as Okta with AWS SSO to keep users and groups in sync. But to avoid any potential mishaps, I recommend restricting access so that IAM user creation is not allowed by general users, only select admins. Even for those select admins, there should be explicit policies where ad-hoc IAM user creation isn't allowed – use roles wherever possible.

In this post, I'll walk through a method to get notified by email whenever an IAM user is created, so you can respond accordingly.

Prerequisite : Cloudtrail and SES should be configured in your AWS account.

Step 1: Create a role for Lambda with the following policy:

1{
2    "Version": "2012-10-17",
3    "Statement": [
4        {
5            "Effect": "Allow",
6            "Action": "ses:SendEmail",
7            "Resource": "*"
8        }
9    ]
10}

Also, add AWSLambdaBasicExecutionRole policy to this role.

Step 2: Create a Lambda function with a Python3.7 runtime and 2-minute timeout. Set 2 environment variables for this function.

Source: email address used to send an email notification. Recipient: receiver’s email address – make sure it’s whitelisted with SES.

Use the code provided at https://raw.githubusercontent.com/vinycoolguy2015/awslambda/master/iam_notification.py for this Lambda function.

1import json
2import boto3
3import os 
4import re
5
6ses_client=boto3.client("ses")
7
8def lambda_handler(event, context):
9   CreatedDate= event['detail']['responseElements']['user']['createDate']
10   Username = event['detail']['responseElements']['user']['userName']
11   CreatedBy=''
12   if event['detail']['userIdentity']['type']=='IAMUser':
13      CreatedBy=event['detail']['userIdentity']['userName']
14   elif event['detail']['userIdentity']['type']=='AssumedRole':
15      CreatedBy=event['detail']['userIdentity']['principalId']
16   pattern = '^d'
17   result = re.match(pattern,Username.lower().strip())
18   if not result:
19      if CreatedBy=='':
20         Data=' User ' +Username + ' got created on ' + CreatedDate
21      else:
22         Data=' User ' +Username + ' got created on ' + CreatedDate + ' by '+CreatedBy
23      print(Data)    
24      send_email("IAM Notification",Data)
25   
26def send_email(subject,body):
27    ses_client.send_email(Source=os.environ['Source'],Destination={'ToAddresses': [os.environ['Recipient']]},
28    Message={
29        'Subject': {
30            'Data': subject
31        },
32        'Body': {
33            'Text': {
34                'Data': body
35            }
36        }
37    }
38)

Note that if you have users that get automatically created by applications such as Hashicorp vault, you can exclude them so that you don’t get unnecessary notifications. For that, modify the pattern variable in the code.

Step 3: Next create a CloudWatch rule which will trigger this Lambda. Use the given event pattern to create the rule. Then add your lambda as a target for this rule, and you're all set!

1{
2  "source": [
3    "aws.iam"
4  ],
5  "detail-type": [
6    "AWS API Call via CloudTrail"
7  ],
8  "detail": {
9    "eventSource": [
10      "iam.amazonaws.com"
11    ],
12    "eventName": [
13      "CreateUser"
14    ]
15  }
16}

Now, any time someone creates an IAM user, you will get an email notification like this:

Photo from Unsplash

    img

    Join the beta waitlist

    Enter your email to get notified when our product becomes available to try.

    Sign Up for the community

    Create your member profile to get involved with our content, programs, and events.