首页 > 解决方案 > AWS Lambda python 函数发送多条 SNS 消息

问题描述

我在 AWS Lambda 函数中有 Python 3.6,它处理每个项目多次而不是一次,我不知道为什么。它正在检查特定标签值并在满足该值时通过 SNS 发送电子邮件,而不是收到一封电子邮件警报,我收到 5 个或更多。

相关代码如下,我有 x 出帐号。

aws_account_numbers = {xxxxxxxxxxx,xxxxxxxxxxx,xxxxxxxxxxx,xxxxxxxxxxx,xxxxxxxxxxx,xxxxxxxxxxx}


def lambda_handler(event, context):
    today = datetime.date.today()
    mdy = today_string = today.strftime('%m/%d/%y')

    for name, acctnum in aws_account_numbers.items():
        roleArn = "arn:aws:iam::%s:role/EOTSS-Monitor-Tags-expenddate" % acctnum
        stsClient = boto3.client('sts')
        sts_response = stsClient.assume_role(RoleArn=roleArn,RoleSessionName='AssumeCrossAccountRole', DurationSeconds=1800)
        ec2 = boto3.resource(service_name='ec2',region_name=region,aws_access_key_id = sts_response['Credentials']['AccessKeyId'],
            aws_secret_access_key = sts_response['Credentials']['SecretAccessKey'], aws_session_token = sts_response['Credentials']['SessionToken'])

        for instance in ec2.instances.all():
            if instance.tags is None:
                continue
            for tag in instance.tags:
                if tag['Key'] == 'expenddate':
                    expiredInstances=[]
                    if (tag['Value']) <= mdy:
                        sns_client.publish(
                            TopicArn = 'arn:aws:sns:us-east-1:xxxxxxxxxxx:EOTSS-Monitor-Tag-Exceptions-Temp',
                            Subject = '!!!! Tag Exception has Expired.',
                            Message = str("The tag exception for instance %s has expired in account %s" % (instance.id,acctnum)))
                else:
                    print ("end")
    return "sucess"

标签: python-3.xamazon-web-servicesaws-lambdaamazon-sns

解决方案


这似乎是导致问题的 SNS 主题。我删除了 SNS 主题并使用稍有不同的名称重新创建它,然后将我的 Lambda 函数指向该主题,几天以来,每个满足条件的实例我只收到一封电子邮件警报。


推荐阅读