Nick Barton-Wells
Nick Barton-Wells

Reputation: 281

Python Lambda - print issues with "list", require line break

I am having issues printing a list out with a new line break after each user and access key has been returned

The Lambda returns:

['Hannah', 1103, 'Nick', 126]

I would like it to return with a line break in after every user and access key age is returned

['Hannah', 1103
'Nick', 126]
import boto3, json, time, datetime, sys

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

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))

    sns_message = (finallist)
    response = sns.publish(
        TopicArn='arn:aws:sns:ARN',
        Message= sns_message,
        Subject='Access Keys which need rotating',
    )

Upvotes: 0

Views: 691

Answers (1)

Bram Vanroy
Bram Vanroy

Reputation: 28437

Seems like you need some kind of prettyprint function to do what you want. The following function does exactly what you want:

result = ['Hannah', 1103, 'Nick', 126]

def prettyprint(l):
    s = '['
    n_items = len(l)
    for idx, item in enumerate(l):
        is_str = isinstance(item, str)
        s += f"'{item}'" if is_str else str(item)
        if idx != n_items-1:
            s += ', ' if is_str else '\n'
    s += ']'
    return s

print(prettyprint(result))

Prints:

['Hannah', 1103
'Nick', 126]

Upvotes: 1

Related Questions