Cloudformation 模板在 S3 事件上触发 Lambda

aid*_*ald 6 amazon-s3 amazon-web-services aws-cloudformation aws-lambda

我想使用 Cloudformation 创建一个 S3 存储桶,该存储桶将在发生文件创建、文件删除等 S3 事件时触发 Lambda 函数。

根据我的研究,我有我的AWS::Lambda::FunctionAWS::S3::Bucket设置,

AWSTemplateFormatVersion: '2010-09-09'
Resources:
  HandleFileCreation: 
    Type: "AWS::Lambda::Function"
    Properties: 
      ...

  LambdaExecutionRole:
    Type: AWS::IAM::Role
    Properties:
      ManagedPolicyArns:
      - arn:aws:iam::aws:policy/AmazonS3FullAccess
      - arn:aws:iam::aws:policy/AWSLambdaFullAccess
      AssumeRolePolicyDocument:
        ...

  ReportsBucket:
    Type: AWS::S3::Bucket

  BucketPolicy:
    Type: AWS::S3::BucketPolicy
    Properties:
      Bucket: !Ref ReportsBucket
      PolicyDocument:
        ...
Run Code Online (Sandbox Code Playgroud)

我正在查看AWS::Events::Rule,但该示例仅适用于 EC2,我找不到 S3 的示例

  EventRule: 
    Type: "AWS::Events::Rule"
    Properties: 
      Description: "EventRule"
      EventPattern: 
        source: 
          - "aws.ec2"
        detail-type: 
          - "EC2 Instance State-change Notification"
        detail: 
          state: 
            - "stopping"
      State: "ENABLED"
      Targets: 
        - 
          Arn: 
            Fn::GetAtt: 
              - HandleFileCreation
              - Arn
          Id: TargetFunctionV1
  PermissionForEventsToInvokeLambda: 
    Type: AWS::Lambda::Permission
    Properties: 
      FunctionName: 
        Ref: HandleFileCreation
      Action: "lambda:InvokeFunction"
      Principal: "events.amazonaws.com"
      SourceArn: 
        Fn::GetAtt: 
          - "EventRule"
          - "Arn"
Run Code Online (Sandbox Code Playgroud)

如何编写模板以在 S3 事件上触发?

Kan*_*yan 8

这是一个例子,

http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket-notificationconfig-lambdaconfig.html

EncryptionServiceBucket:
  Type: "AWS::S3::Bucket"
  Properties:
    BucketName: !Sub ${User}-encryption-service
    NotificationConfiguration:
      LambdaConfigurations:
        -
          Function: !Ref LambdaDeploymentArn
          Event: "s3:ObjectCreated:*"
          Filter:
            S3Key:
              Rules:
                -
                  Name: suffix
                  Value: zip
Run Code Online (Sandbox Code Playgroud)

我注意到的一个问题是,您需要先创建函数,然后再为其分配触发器。如果您正在使用 CF,请确保在为其创建触发器之前创建 lambda 函数。

希望能帮助到你。