如上面標題中所述,我希望每次將文件上傳到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