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:
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 reses_client=boto3.client("ses")def send_email(subject,body):
def lambda_handler(event, context):
Username = event['detail']['responseElements']['user']['userName']
pattern = '^exclude-user'
result = re.match(pattern,Username.lower().strip())
if not result:
Data=' User ' +Username + ' got created on ' + CreatedDate
Data=' User ' +Username + ' got created on ' + CreatedDate + ' by '+CreatedBy
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.
"AWS API Call via CloudTrail"
Now, let’s create an IAM user and you should get an email notification like this: