gpt4 book ai didi

amazon-web-services - 使用 AWS CloudFormation 设置 S3 存储桶级别事件

转载 作者:行者123 更新时间:2023-12-03 07:43:31 31 4
gpt4 key购买 nike

我正在尝试让 AWS CloudFormation 创建一个模板,该模板允许我将一个事件附加到现有 S3 存储桶,每当将新文件放入存储桶中的特定目录时,该事件就会触发 Lambda 函数。我使用以下 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 }'

我尝试用多种不同的方式重写此模板,但没有成功。

最佳答案

既然您提到这些存储桶已经存在,那么这是行不通的。您可以通过这种方式使用 CloudFormation,但只能创建一个新存储桶,而不能修改现有存储桶(如果该存储桶最初不是通过该模板创建的)。

如果您不想重新创建基础架构,那么使用一些脚本将 lambda 函数订阅到每个存储桶可能会更容易。只要您有存储桶列表和 lambda 函数,就可以开始了。

这是 Python3 中的脚本。假设我们有:

  1. 2 个名为 test-bucket-jkg2test-bucket-x1gf
  2. 的存储桶
  3. 带有 arn 的 lambda 函数:arn:aws:lambda:us-east-1:605189564693:function:my_func

完成这项工作需要两个步骤。首先,您需要添加允许 s3 服务执行该函数的函数策略。其次,您将一一循环存储桶,为每个存储桶订阅 lambda 函数。

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)

关于amazon-web-services - 使用 AWS CloudFormation 设置 S3 存储桶级别事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58739265/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com