如上面标题中所述,我希望每次将文件上传到s3存储桶时都会收到电子邮件,但我使用无服务器,问题在于我创建的事件在s3上,我只是通知s3-aws控制台,并不知道如何在S3上配置cloudwatch事件来触发lambda。所以,如果有人知道如何使用cloudwatch在S3上触发事件,我非常高兴。 这里是我的代码:每当使用无服务器将文件上传到s3存储桶时获取电子邮件
import json
import boto3
import botocore
import logging
import sys
import os
import traceback
from botocore.exceptions import ClientError
from pprint import pprint
from time import strftime, gmtime
email_from = '*****@******.com'
email_to = '******@******.com'
#email_cc = '********@gmail.com'
email_subject = 'new event on s3 '
email_body = 'a new file is uploaded'
#setup simple logging for INFO
logger = logging.getLogger()
logger.setLevel(logging.INFO)
from botocore.exceptions import ClientError
def sthree(event, context):
"""Send email whenever a file is uploaded to S3"""
body = {}
status_code = 200
try:
s3 = boto3.client('s3')
ses = boto3.client('ses')
response = ses.send_email(Source = email_from,
Destination = {'ToAddresses': [email_to,],},
Message = {'Subject': {'Data': email_subject}, 'Body':{'Text' : {'Data': email_body}}}
)
response = {
"statusCode": 200,
"body": json.dumps(body)
}
return response
,这里是我的serverless.yml文件
service: aws-python # NOTE: update this with your service name
plugins:
- serverless-external-s3-event
provider: name: aws
runtime: python2.7
stage: dev
region: us-east-1
iamRoleStatements:
- Effect: "Allow"
Action:
- s3:*
- "ses:SendEmail"
- "ses:SendRawEmail"
- "s3:PutBucketNotification"
Resource: "*"
functions: sthree:
handler: handler.sthree
description: send mail whenever a file is uploaded on S3
events:
- s3:
bucket: cartegie-nirmine
event: s3:ObjectCreated:*
rules:
- prefix: uploads/
- suffix: .jpg
- cloudwatchEvent:
description: 'CloudWatch Event triggered '
event:
source:
- "aws.S3"
detail-type:
- "S3 event Notification"
enabled : true
看起来你有一个由上传事件触发的lambda。这个lambda应该是发送电子邮件的,对吧?你是否检查过lambda的日志以查看是否有错误?我建议你记录事件以确保你正在接收它。 –
除非您需要通过编写代码提供的灵活性,否则您可以简单地配置S3事件以发布到SNS主题并通过电子邮件地址订阅该主题。 – jarmod