Get Email notification on AWS IAM user creation

Vinayak Pandey
2 min readJul 23, 2020

--

In an Enterprise environment, keeping track of IAM users is a tedious task. To avoid any mishaps, we should have restricted access so that IAM user creation is not allowed by users, except admins. Even for admins, we should have polices where ad-hoc IAM user creation shouldn’t be allowed(use roles wherever possible). In this post, we’ll see how we can get notified whenever an IAM user is created.

Pre- requisite: Cloudtrail and SES should be configured in your AWS account.

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

{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "VisualEditor0",
"Effect": "Allow",
"Action": "ses:SendEmail",
"Resource": "*"
}
]
}

Also add AWSLambdaBasicExecutionRole policy to this role.

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

Source: email address used to send email notification

Recipient: receiver’s email address, make sure it’s whitelisted with SES.

Use the given code for Lambda:

import json
import boto3
import os
import re
ses_client=boto3.client("ses")def send_email(subject,body):
ses_client.send_email(Source=os.environ['Source'],Destination={'ToAddresses': [os.environ['Recipient']]},
Message={
'Subject': {
'Data': subject
},
'Body': {
'Text': {
'Data': body
}
}
}
)

def lambda_handler(event, context):
CreatedDate= event['detail']['responseElements']['user']['createDate']
Username = event['detail']['responseElements']['user']['userName']
CreatedBy=''
if event['detail']['userIdentity']['type']=='IAMUser':
CreatedBy=event['detail']['userIdentity']['userName']
elif event['detail']['userIdentity']['type']=='AssumedRole':
CreatedBy=event['detail']['userIdentity']['principalId']
pattern = '^exclude-user'
result = re.match(pattern,Username.lower().strip())
if not result:
if CreatedBy=='':
Data=' User ' +Username + ' got created on ' + CreatedDate
else:
Data=' User ' +Username + ' got created on ' + CreatedDate + ' by '+CreatedBy
send_email("IAM Notification",Data)

If there are users which get automatically created by applications(like Hashicorp vault), you can exclude them so that we don’t get unnecessary notifications. For that modify pattern variable in the code.

Step 3: Now create a CloudWatch rule which will trigger this Lambda. Use the given event pattern to create this rule. Add your lambda as target for this rule and we are all set.

{
"source": [
"aws.iam"
],
"detail-type": [
"AWS API Call via CloudTrail"
],
"detail": {
"eventSource": [
"iam.amazonaws.com"
],
"eventName": [
"CreateUser"
]
}
}

Now, let’s create an IAM user and you should get an email notification like this:

--

--

Vinayak Pandey
Vinayak Pandey

Written by Vinayak Pandey

Experienced Cloud Engineer with a knack of automation. Linkedin profile: https://www.linkedin.com/in/vinayakpandeyit/

Responses (1)