AWS Lambda, Boto3 and IAM – Part 1

coding aws lambda & boto3 python

I’m in the middle of coding an AWS Lambda function to look for users with passwords or access keys that haven’t been used in 45 or 90 days.

If credentials have not been used for 45 days, then the account should be disabled and after 90 days the account should be deleted.

This is my first AWS Lambda project. It has required learning the boto3 libraries functions in order to get the data out of IAM.

I am building and testing it in my remote development environment.

So far, I have the days since last use for both passwords and access keys. next steps will be to take action on the credentials.

#!/usr/bin/python3

import boto3, time, sys
from datetime import date

#def lambda_handler(event, context):
# Create IAM client
client = boto3.client('iam')
resource = boto3.resource('iam')

current_date = date.today()

for user in client.list_users()['Users']:
	if "PasswordLastUsed" in user:
		pwd_last_used = user['PasswordLastUsed'].date()
		days_since_pwd_used = current_date - pwd_last_used
		
		print("User: {0}\nUserID: {1}\nARN: {2}\nCreatedOn: {3}\nDays Since Password Used: {4}\n".format(			
			user['UserName'],
			user['UserId'],
			user['Arn'],
			user['CreateDate'].date(),
			days_since_pwd_used
			)
		)
	else:
		user_name = user['UserName']
		id = user['UserId']
		arn = user['Arn']
		result_list_keys = client.list_access_keys(UserName=user_name)
		access_key = (result_list_keys['AccessKeyMetadata'][0]['AccessKeyId'])
		create_date = (result_list_keys['AccessKeyMetadata'][0]['CreateDate']).date()
		LastUsed = client.get_access_key_last_used(AccessKeyId=access_key)

		if 'LastUsedDate' in LastUsed['AccessKeyLastUsed']:
			key_last_used = LastUsed['AccessKeyLastUsed']['LastUsedDate'].date()
			days_since_key_used = current_date - key_last_used

			print("User: {0}\nUserID: {1}\nARN: {2}\nCreated On: {3}\nDays Since Key Used: {4}\n".format(
				user_name,
				id,
arn, create_date, days_since_key_used ) )