Any lambda/python gurus who can help?

Any lambda/python gurus who can help?

Author
Discussion

Too Late

Original Poster:

5,094 posts

235 months

Thursday 22nd October 2020
quotequote all
Hi all
I am getting an issue when returning a list of users and their accesskeys which are over X number of days old.
I am lead to believe its truncated and i need to use boto/python paginator

I am really struggling to implement this into my lambda. Is anyone able to help?
Thank

     import boto3, json, time, datetime, sys, pprint

sns = boto3.client('sns')
usernames = []
mylist = []

sts_client = boto3.client('sts')
assumed_role_object=sts_client.assume_role(
RoleArn="arn:aws:iam::11111111:role/lambda_role",
RoleSessionName="AssumedRoleSession4"
)
credentials=assumed_role_object['Credentials']
client=boto3.client(
'iam',
aws_access_key_id=credentials['AccessKeyId'],
aws_secret_access_key=credentials['SecretAccessKey'],
aws_session_token=credentials['SessionToken'],
)

def lambda_handler(event, context):
users = client.list_users()
for key in users['Users']:
a = str(key['UserName'])
usernames.append(a)
for username in usernames:
try:
res = client.list_access_keys(UserName=username)
accesskeydate = res['AccessKeyMetadata'][0]['CreateDate']
accesskeydate = accesskeydate.strftime("%Y-%m-%d %H:%M:%S")
currentdate = time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime())
accesskeyd = time.mktime(datetime.datetime.strptime(accesskeydate, "%Y-%m-%d %H:%M:%S").timetuple())
currentd = time.mktime(datetime.datetime.strptime(currentdate, "%Y-%m-%d %H:%M:%S").timetuple())
active_days = (currentd - accesskeyd)/60/60/24 ### We get the data in seconds. converting it to days

if 90 < active_days:
a = str(username)
c = int(int(round(active_days)))

mylist.append(a)
mylist.append(c)
except:
f = str('')

print(mylist)
finallist = ''.join(str(mylist))
finallist = finallist

sns_message = (finallist)
response = sns.publish(
TopicArn='arn:aws:sns:eu-west-2:111111:sns',
Message= sns_message,
Subject='Access Keys which need rotating',
)

Ynox

1,704 posts

179 months

Saturday 24th October 2020
quotequote all
Your script looks vaguely reasonable at a glance.

Probably stating the obvious, but I found the boto3 docs to be fairly reasonable and Google had decent examples last time I was doing some Python scripting for AWS.

What part do you think requires pagination? The keys?