简体   繁体   中英

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

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM