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"

应添加其他调试代码以确认多次调用publish()命令。

例如:

for instance in ec2.instances.all():
if instance.tags is None:
continue
for tag in instance.tags:
print('Checking instance: ', instance.id)   # <-- Added
if tag['Key'] == 'expenddate':
expiredInstances=[]
if (tag['Value']) <= mdy:
print('Sending publish message')    # <-- Added
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)))

这将帮助您确定代码是发送多条消息,还是 Amazon SNS 多次发送一条消息。

顺便说一下,我可以看到region在您的代码中定义的位置,但我看不到正在使用expiredInstances

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

最新更新