Home > database >  How to send the results of a lambda function to an email using aws sns
How to send the results of a lambda function to an email using aws sns

Time:09-29

I have a lambda function that generates a list of users that are without MFA active, after generating this list, I wanted to send the output by email using SNS, but the current way it sends one user at a time and if I leave the publish outside the function, only a name is sent

    import json
    import boto3

def lambda_handler(event, context):
    sns_resource = boto3.resource('sns')
    TOPIC_ARN = 'sns_topic_arn'
    sns_topic = sns_resource.Topic(TOPIC_ARN)
    
    iam = boto3.resource('iam')
    users = iam.users.all()
    

    for user in users:
        has_any = any(user.mfa_devices.all())
        if not has_any:
            print(user.name)
            
    sns_topic.publish(Message=user.name)

CodePudding user response:

So you basically just need to collect the names outside the loop and push that into the message to SNS. Using join is a common pattern. Something like this:

import json
import boto3

def lambda_handler(event, context):
    sns_resource = boto3.resource('sns')
    TOPIC_ARN = 'sns_topic_arn'
    sns_topic = sns_resource.Topic(TOPIC_ARN)
    
    iam = boto3.resource('iam')
    users = iam.users.all()
    
    naughty_list = []
    for user in users:
        has_any = any(user.mfa_devices.all())
        if not has_any:
            naughty_list.append(user.name)
            
    sns_topic.publish(Message="Naughty list users: \n{}".format("\n".join(naughty_list)))
  • Related