简体   繁体   English

使用 AWS CloudFormation 设置 S3 存储桶级事件

[英]Set up S3 Bucket level Events using AWS CloudFormation

I am trying to get AWS CloudFormation to create a template that will allow me to attach an event to an existing S3 Bucket that will trigger a Lambda Function whenever a new file is put into a specific directory within the bucket.我正在尝试让 AWS CloudFormation 创建一个模板,该模板允许我将一个事件附加到现有的 S3 存储桶,只要将新文件放入存储桶中的特定目录,就会触发 Lambda Function。 I am using the following YAML as a base for the CloudFormation template but cannot get it working.我正在使用以下 YAML 作为 CloudFormation 模板的基础,但无法使其正常工作。

---
AWSTemplateFormatVersion: '2010-09-09'
Resources:
  SETRULE:
    Type: AWS::S3::Bucket
      Properties:
        BucketName: bucket-name
        NotificationConfiguration:
          LambdaConfigurations: 
            - Event: s3:ObjectCreated:Put
              Filter: 
                S3Key:
                  Rules:
                    - Name: prefix
                      Value: directory/in/bucket
              Function: arn:aws:lambda:us-east-1:XXXXXXXXXX:function:lambda-function-trigger
              Input: '{ CONFIGS_INPUT }'

I have tried rewriting this template a number of different ways to no success.我尝试用多种不同的方法重写这个模板,但都没有成功。

Since you have mentioned that those buckets already exists, this is not going to work.由于您提到这些存储桶已经存在,因此这是行不通的。 You can use CloudFormation in this way but only to create a new bucket, not to modify existing bucket if that bucket was not created via that template in the first place.您可以通过这种方式使用 CloudFormation,但只能创建一个新的存储桶,如果该存储桶最初不是通过该模板创建的,则不能修改现有的存储桶。

If you don't want to recreate your infrastructure, it might be easier to just use some script that will subscribe lambda function to each of the buckets.如果您不想重新创建您的基础架构,则使用一些脚本可能会更容易,这些脚本将订阅 lambda function 到每个存储桶。 As long as you have a list of buckets and the lambda function, you are ready to go.只要你有一个桶列表和 lambda function,你就准备好了 go。

Here is a script in Python3.这是 Python3 中的脚本。 Assuming that we have:假设我们有:

  1. 2 buckets called test-bucket-jkg2 and test-bucket-x1gf 2 个称为test-bucket-jkg2test-bucket-x1gf 的存储桶
  2. lambda function with arn: arn:aws:lambda:us-east-1:605189564693:function:my_func lambda function with arn: arn:aws:lambda:us-east-1:605189564693:function:my_func

There are 2 steps to make this work.有两个步骤可以完成这项工作。 First, you need to add function policy that will allow s3 service to execute that function.首先,您需要添加 function 策略,该策略将允许 s3 服务执行该 function。 Second, you will loop through the buckets one by one, subscribing lambda function to each one of them.其次,您将逐个遍历存储桶,为每个存储桶订阅 lambda function。

import boto3

s3_client = boto3.client("s3") 
lambda_client = boto3.client('lambda')

buckets = ["test-bucket-jkg2", "test-bucket-x1gf"]
lambda_function_arn = "arn:aws:lambda:us-east-1:605189564693:function:my_func"

# create a function policy that will permit s3 service to 
# execute this lambda function

# note that you should specify SourceAccount and SourceArn to limit who (which account/bucket) can
# execute this function - you will need to loop through the buckets to achieve 
# this, at least you should specify SourceAccount
try:
    response = lambda_client.add_permission(
        FunctionName=lambda_function_arn,
        StatementId="allow s3 to execute this function",
        Action='lambda:InvokeFunction',
        Principal='s3.amazonaws.com'
        # SourceAccount="your account",
        # SourceArn="bucket's arn"
    )
    print(response)
except Exception as e:
    print(e)

# loop through all buckets and subscribe lambda function 
# to each one of them
for bucket in buckets:
    print("putting config to bucket: ", bucket)
    try:
        response = s3_client.put_bucket_notification_configuration(
            Bucket=bucket,
            NotificationConfiguration={
                'LambdaFunctionConfigurations': [
                    {
                        'LambdaFunctionArn': lambda_function_arn,
                        'Events': [
                            's3:ObjectCreated:*'
                        ]
                    }
                ]
            }
        )
        print(response)
    except Exception as e:
        print(e)

You could write a custom resource to do this, in fact that's what I've ended up doing at work for the same problem.您可以编写一个自定义资源来执行此操作,实际上这就是我最终在工作中针对同一问题所做的工作。 At the simplest level, define a lambda that takes a put bucket notification configuration and then just calls the put bucket notification api with the data that was passed it.在最简单的级别上,定义一个 lambda,它接受一个 put bucket 通知配置,然后使用传递给它的数据调用 put bucket 通知 api。

If you want to be able to control different notifications across different cloudformation templates, then it's a bit more complex.如果您希望能够跨不同的 cloudformation 模板控制不同的通知,那就有点复杂了。 Your custom resource lambda will need to read the existing notifications from S3 and then update these based on what data was passed to it from CF.您的自定义资源 lambda 将需要从 S3 读取现有通知,然后根据从 CF 传递给它的数据更新这些通知。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 AWS Cloudformation模板 - 在S3存储桶中设置区域 - AWS Cloudformation Template - Set Region in S3 Bucket 使用 CloudFormation 在现有 AWS S3 存储桶中创建文本文件 - Create a text file in an existing AWS S3 bucket using CloudFormation CloudFormation资源AWS :: S3 :: Bucket未显示在S3控制台中 - CloudFormation resource AWS::S3::Bucket doesn't show up in S3 console aws lambda - 如果手动创建 s3 存储桶,如何使用 cloudformation 添加 s3 触发器 - aws lambda - How to add s3 trigger using cloudformation if the s3 bucket is created manually 在未设置权限的情况下对AWS S3存储桶访问被拒绝 - Access Denied on AWS S3 bucket with no permission set up 如何使用 python 中的 aws-cdk 设置 Amazon S3 通知以在您的存储桶中发生某些事件时接收通知? - How do I set up Amazon S3 notification to receive notifications when certain events happen in your bucket using aws-cdk in python? 使用 webhooks 与 gitLabs 链接时,AWS Cloudformation 在 AWS S3 存储桶中的 zip 内创建一个子文件夹 - AWS Cloudformation when linked with gitLabs using webhooks creates a subfolder inside zip in AWS S3 bucket 如何使用Cloudformation将代码从aws s3存储桶安全地提取到Codecommit存储库? - How to securely pull code from an aws s3 bucket to a Codecommit repository using Cloudformation? 如何使用 Cloudformation 从 S3 存储桶中的代码创建 AWS 代码提交存储库 - How to create an AWS codecommit repo using Cloudformation from code in an S3 bucket AWS - 使用 CloudFormation 将数据从一个 S3 存储桶移动到另一个存储桶 - AWS - Moving data from one S3 bucket to another with CloudFormation
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM