无法使用 boto3 为 lambda 添加 s3 通知

Can't add s3 notification for lambda using boto3

我想使用 boto3 配置 s3 存储桶,以便每次在该存储桶中创建对象时调用 AWS lambda。这是我的代码:

s3 = ..boto3 resource
bucket_notification = s3.BucketNotification(bucket_name)
lambda_arn = .. arn for lambda

response = bucket_notification.put(
   NotificationConfiguration={'LambdaFunctionConfigurations': [
      {
                'LambdaFunctionArn': lambda_arn,
                'Events': [
                    's3:ObjectCreated:*'
                ],

      },
]})

我收到错误:

botocore.exceptions.ClientError: An error occurred (InvalidArgument) when calling the PutBucketNotificationConfiguration operation: Unable to validate the following destination configurations

必须在 lambda 端添加权限以允许 S3 调用 lambda 函数。请注意,如果您使用 AWS Lambda GUI 手动创建事件源映射,然后删除事件源映射,权限仍然存在!所以你不会得到上面的错误。

但是,如果您从头开始,然后尝试添加通知,则会出现上述错误。

权限添加者:

 client = ...boto3 lambda client
 response = client.add_permission(
     FunctionName=lambda_name,
     StatementId='1',
     Action='lambda:InvokeFunction',
     Principal='s3.amazonaws.com',
     SourceArn=s3_arn,
     SourceAccount='66666666666'
 )

我以前遇到过这个问题 - 你绝对应该考虑@RAbraham 对这个问题的回答,但你可能还想检查一件事;

检查您的 s3 存储桶中是否有任何事件是孤立的,即如果删除了 lambda 函数,您也必须删除相应的 s3 事件(如果存在)。如果您不这样做并尝试 add/edit 同一存储桶上的任何事件,它会给您同样的错误。

如果 lambda 不存在,它就无法更新整个存储桶的通知配置,无论您正在更新哪个事件,因为它本质上是原子的 (aws-source)。

参考:https://docs.aws.amazon.com/cli/latest/reference/s3api/put-bucket-notification-configuration.html

ANSIBLE SCRIPT:不要在 'event_name' 值

中提供空格


---
- name: deploy lambda
   hosts: localhost
   connection: local
   gather_facts: false 

tasks:
 - name: add lambda event notification for a bucket
     s3_bucket_notification:
       state: present
       event_name: Test1_lambda_Event_name
       bucket_name: test-private
       lambda_function_arn: arn:aws-us-xxxxxlambda
       events: ["s3:ObjectCreated:*"]
       prefix: Test_R/configuration      
     register: output 
     ignore_errors: true
     
   - name: debug output
     debug:
       msg: "output is: {{output}}"