跳至內容

如何使用 CloudFormation,在現有的 S3 儲存貯體上為 Lambda 建立 Amazon S3 通知組態?

3 分的閱讀內容
0

我想使用現有的 Amazon Simple Storage Service (Amazon S3) 儲存貯體,為 AWS Lambda 函式建立 Amazon S3 通知組態。

簡短描述

若要建立 Amazon S3 通知組態,請使用 CloudFormation 建立新的 S3 儲存貯體。接著,使用 NotificationConfiguration 屬性,將通知組態新增至該儲存貯體。或者,手動將通知組態新增至現有的 S3 儲存貯體。

以下步驟說明如何使用 CloudFormation,將通知組態新增至現有的 S3 儲存貯體。若要這麼做,請使用 Python 3.9 建立以 Lambda 為後端的自訂資源。自訂資源會啟動 Lambda 函式,由該函式呼叫 PutBucketNotification API,將通知組態新增至您的 S3 儲存貯體。

注意: 若您執行 AWS Command Line Interface (AWS CLI) 命令時遇到錯誤,請確認您使用的是最新的 AWS CLI 版本。

解決方法

重要: 以下步驟僅適用於尚未設定通知組態的 S3 儲存貯體,用來為其設定 Amazon S3 通知。若您的 S3 儲存貯體已有通知組態,包括手動建立的通知組態,以下步驟將覆寫這些組態。您刪除堆疊後,Amazon S3 會移除所有通知。即使解決方案看似能正常運作,您的使用案例中仍可能存在不理想的組態。最佳實務是在部署至實際執行環境前,先在測試用的 S3 儲存貯體上測試解決方案。

1.    建立名為 LambdaS3.template 的 CloudFormation 範本,並納入以下程式碼:

重要: 在以下範例中,您會將 S3 通知組態新增至 S3NotificationLambdaFunction 資源。您會使用 Lambda 函式 CustomResourceLambdaFunction,為 S3NotificationLambdaFunction 新增 S3 通知組態。您可以修改 CustomResourceLambdaFunction 資源中的程式碼,以符合您的需求。

AWSTemplateFormatVersion: 2010-09-09
Description: >-
  Sample template to illustrate use of existing S3 bucket as an event source for a Lambda function
Parameters:
  NotificationBucket:
    Type: String
    Description: S3 bucket that's used for the Lambda event notification

Resources:
  S3NotificationLambdaFunction:
    Type: 'AWS::Lambda::Function'
    Properties:
      Code:
        ZipFile: !Join
          - |+

          - - import json
            - 'def lambda_handler(event,context):'
            - '    return ''Welcome... This is a test Lambda Function'''
      Handler: index.lambda_handler
      Role: !GetAtt LambdaIAMRole.Arn
      Runtime: python3.9
      Timeout: 5

  LambdaInvokePermission:
    Type: 'AWS::Lambda::Permission'
    Properties:
      FunctionName: !GetAtt S3NotificationLambdaFunction.Arn
      Action: 'lambda:InvokeFunction'
      Principal: s3.amazonaws.com
      SourceAccount: !Ref 'AWS::AccountId'
      SourceArn: !Sub 'arn:aws:s3:::${NotificationBucket}'

  LambdaIAMRole:
    Type: 'AWS::IAM::Role'
    Properties:
      AssumeRolePolicyDocument:
        Version: 2012-10-17
        Statement:
          - Effect: Allow
            Principal:
              Service:
                - lambda.amazonaws.com
            Action:
              - 'sts:AssumeRole'
      Path: /
      Policies:
        - PolicyName: root
          PolicyDocument:
            Version: 2012-10-17
            Statement:
              - Effect: Allow
                Action:
                  - 's3:GetBucketNotification'
                  - 's3:PutBucketNotification'
                Resource: !Sub 'arn:aws:s3:::${NotificationBucket}'
              - Effect: Allow
                Action:
                  - 'logs:CreateLogGroup'
                  - 'logs:CreateLogStream'
                  - 'logs:PutLogEvents'
                Resource: 'arn:aws:logs:*:*:*'

  CustomResourceLambdaFunction:
    Type: 'AWS::Lambda::Function'
    Properties:
      Handler: index.lambda_handler
      Role: !GetAtt LambdaIAMRole.Arn
      Code:
        ZipFile: |

            from __future__ import print_function
            import json
            import boto3
            import cfnresponse

            SUCCESS = "SUCCESS"
            FAILED = "FAILED"

            print('Loading function')
            s3 = boto3.resource('s3')

            def lambda_handler(event, context):
                print("Received event: " + json.dumps(event, indent=2))
                responseData={}
                try:
                    if event['RequestType'] == 'Delete':
                        print("Request Type:",event['RequestType'])
                        Bucket=event['ResourceProperties']['Bucket']
                        delete_notification(Bucket)
                        print("Sending response to custom resource after Delete")
                    elif event['RequestType'] == 'Create' or event['RequestType'] == 'Update':
                        print("Request Type:",event['RequestType'])
                        LambdaArn=event['ResourceProperties']['LambdaArn']
                        Bucket=event['ResourceProperties']['Bucket']
                        add_notification(LambdaArn, Bucket)
                        responseData={'Bucket':Bucket}
                        print("Sending response to custom resource")
                    responseStatus = 'SUCCESS'
                except Exception as e:
                    print('Failed to process:', e)
                    responseStatus = 'FAILED'
                    responseData = {'Failure': 'Something bad happened.'}
                cfnresponse.send(event, context, responseStatus, responseData, "CustomResourcePhysicalID")

            def add_notification(LambdaArn, Bucket):
                bucket_notification = s3.BucketNotification(Bucket)
                response = bucket_notification.put(
                  NotificationConfiguration={
                    'LambdaFunctionConfigurations': [
                      {
                          'LambdaFunctionArn': LambdaArn,
                          'Events': [
                              's3:ObjectCreated:*'
                          ]
                      }
                    ]
                  }
                )
                print("Put request completed....")

            def delete_notification(Bucket):
                bucket_notification = s3.BucketNotification(Bucket)
                response = bucket_notification.put(
                    NotificationConfiguration={}
                )
                print("Delete request completed....")
      Runtime: python3.9
      Timeout: 50

  LambdaTrigger:
    Type: 'Custom::LambdaTrigger'
    DependsOn: LambdaInvokePermission
    Properties:
      ServiceToken: !GetAtt CustomResourceLambdaFunction.Arn
      LambdaArn: !GetAtt S3NotificationLambdaFunction.Arn
      Bucket: !Ref NotificationBucket

2.    若要使用 LambdaS3.template 檔案啟動 CloudFormation 堆疊,請使用 CloudFormation 主控台或以下 AWS CLI 命令:

aws cloudformation create-stack --stack-name lambda-s3-notification --template-body file://LambdaS3.template --parameters ParameterKey=NotificationBucket,ParameterValue=existing-bucket-for-lambda-notification --capabilities CAPABILITY_NAMED_IAM --region us-east-1

重要: 啟動 CloudFormation 堆疊時,您必須傳入 S3 儲存貯體名稱。例如,執行命令時傳入 existing-bucket-for-lambda-notification。

堆疊會為 Amazon S3 建立 Lambda 函式與 Lambda 權限。堆疊已將所需的通知組態新增至您的 S3 儲存貯體,因此您現在可以使用該儲存貯體來處理 Lambda 通知。